//批量添加密码
function addPwds(){
    mccmsa.ajax({
        url:"centerControl/findControlByLike",
        method:"post",
        data:{likeStr:""},
        success:function(data){
            mccmsa.getHtmlFromLocalTemplate({
                templateId: "resultx_temp",
                container: $("#resultX"),
                data: data
            });
        }
    })
}

/*异步搜索*/
var mynewtime='';
var myoldtime='';
var myoldT = 0;
function mySearch(callback){
   // clearTimeout(myoldtime);
    mynewtime=setTimeout(function(){
        callback();
    },0);
   /* myoldtime=mynewtime;
    if(new Date().getTime()-myoldT<=1000){
        clearTimeout(myoldtime);
    }
    myoldT = new Date().getTime();*/
}
var ap_scArea=[];
$("body").on("input propertychange","#searchX",function(){
    var value=$(this).val();
   mySearch(function(){
       $.ajax({
           url:"centerControl/findControlByLike",
           method:"post",
           data:{likeStr:value},
           success:function(data){
               data.result=solveData(data.result);
               mccmsa.getHtmlFromLocalTemplate({
                   templateId: "resultx_temp",
                   container: $("#resultX"),
                   data:data
               });
           }
       })
   })
});

function solveData(arr){
    for(var i=0;i<arr.length;i++){
        for(var j=0;j<ap_scArea.length;j++){
            if(arr[i].id==ap_scArea[j].id){
              arr[i].isSC=1;
              break;
            }
        }
    }
    return arr;
}
$("body").on("click",".item_x",function(){
    if($(this).hasClass("active")) return;
    var id=$(this).attr("data-id");
    var name=$(this).attr("title");
    ap_scArea.push({id:id,name:name});
    $(this).addClass("active");
    $("#sc_area").append('<li class="item_r" data-id="'+id+'"><b class="r_reduce">-</b>'+name+'</li>')
});
$("body").on("click",".item_r",function(){
    ap_scArea.splice($(this).index(),1);
    var id=$(this).attr("data-id");
    $(this).remove();
    $("#resultX li[data-id='"+id+"']").removeClass("active");
});
function subPmPwds(){
    var json=$("#sc_pwds_form").serializeJson();
    console.log(json);
    var subdata=[];
    if(json.type==0){
        for(var i=0;i<ap_scArea.length;i++){
            subdata[i]={centerControlId:ap_scArea[i].id,type:json.type};
        }
    }else{
        for(var i=0;i<ap_scArea.length;i++){
            subdata[i]={centerControlId:ap_scArea[i].id,type:json.type,beginTime:json.beginTime,endTime:json.endTime};
        }
    }
    console.log(subdata);
    $.ajax({
        url:"devicePwdInfo/addPwds",
        method:"post",
        data:subdata,
        success:function(data){
            $('#suc_sc').modal('show');
        }
    })
}
function goLookScList(){
     mccmsa.goTo("addPwds_record","addPwds");
}

/*批量修改管家密码*/
function addPwdsMan(){
    mccmsa.ajax({
        url:"centerControl/findControlByLike",
        method:"post",
        data:{likeStr:""},
        success:function(data){
            mccmsa.getHtmlFromLocalTemplate({
                templateId: "resultx_temp",
                container: $("#resultX"),
                data: data
            });
        }
    })
}
var yzCodeLock=false;
function getYzCode(node){
    if(yzCodeLock)  return;
    yzCodeLock=true;
    mccmsa.ajax({
        url:"message/getMobileAuthCode/editPwd/"+sessionStorage.getItem("mobile"),
        method:"get",
        success:function(data){
            calCodeTime(function(times){
                $(node).removeClass("btn-danger").addClass("disabled").html(times+"秒后重新获取");
                yzCodeLock=true;
            },function(){
                $(node).removeClass("disabled").addClass("btn-danger").html("获取验证码");
                yzCodeLock=false;
            })
        },
        error:function(){
            yzCodeLock=false;
        }
    });

}
function calCodeTime(callback,callback2){
    var times=59;
    callback(times);
    var id=setInterval(function(){
        times--;
        callback(times);
        if(times==0){
            clearTimeout(id);
            callback2();
        }
    },1000)
}
function editPwdsMan(){
    var ids=[];
    for(var i=0;i<$(".item_r").length;i++){
       ids[i]=$(".item_r").eq(i).attr("data-id");
    }
    mccmsa.ajax({
        url:"devicePwdInfo /editPwds",
        method:"post",
        data:{centerControllerId:ids.join(","),password:$("#manPwds").val(),code:$("#mancode").val()},
        success:function(data){
            $.bbq.goBack();
        }
    })
}
/*
$("body").on("input propertychange","#manPwds2",function(){
   if($(this).val()!=$("#manPwds").val()){
      $("#pwd_error").show();
   }else{
       $("#pwd_error").hide();
   }
});*/

//批量临时密码记录
function addPwdsRecord(){
    mccmsa.ajax({
        url:"devicePwdInfo/getPwdInfoRecord", //没有接口
        method:"post",
        success:function(data){
            mccmsa.getHtmlFromLocalTemplate({
                templateId:"pwds_record_data_table",
                container:$("#pwds_record_data"),
                data:data
            });
        }

    })
}

/**
 * Created by Jay on 2016/5/20.
 */
function add_derice(){
    flash_fs();
   var time= setInterval(flash_fs,5000);
    $("body").on("click",".add_address",function(){
        var version=$(this).attr("data-version");
        var contract=$(this).attr("data-contractNum");
        var id=$(this).attr("data-id");
        var username=$(this).attr("data-username");
        var mac=$(this).prev().html();
        clearInterval(time);
        mccmsa.goTo("add_device_detail","add_device",{version:version,contract:contract,id:id,username:username,mac:mac});
    })
    function flash_fs(){
        mccmsa.ajax({
            url:"centerControl/findUnAddControl",
            method:"get",
            success: function (data) {
                console.log(data);
                mccmsa.getHtmlFromLocalTemplate({
                    templateId: "add_device_s",
                    container: $("#add_device_container"),
                    data: data
                });
            }
        })
    }
}

/**
 * Created by Jay on 2016/5/24.
 */
function add_device_detail(){
    $(".add_device_form").validate();//绑定表单
   //city
    var str="";
    for(var i=0;i<province.length;i++){
        str+="<option value='"+province[i].provinceid+"'>"+province[i].province+"</option>";
    }
    $("#province").append(str);
    initCity();
   //city end
    var version=$.bbq.getState("version");
    var contract=$.bbq.getState("contract");
    var mac= $.bbq.getState("mac");
    var username= $.bbq.getState("username");
    var id=$.bbq.getState("id");
    //getdata
    var room=$(".add_device_form input").eq(0).val();
    var centerControl={};
    $(".save_btn").on("click",function(){
        var pro=$(".select_city li").eq(0).find("option:selected").val();
        var city=$(".select_city li").eq(1).find("option:selected").val();
        var area=$(".select_city li").eq(2).find("option:selected").val();
        var account=$(".add_device_form input").eq(1).val();
        var contract_1=$(".add_device_form input").eq(2).val();
        var x={id:id,username:account,contractNum:contract_1,provinceId:pro,cityId:city,areaId:area,address:room};
        //console.log(x);
        if(!$(".add_device_form").valid()) return;//如果不正确就跳出
        mccmsa.ajax({
            url:"centerControl/addCenterControl",
            method:"POST",
            data:{id:id,username:account,contractNum:contract_1,provinceId:pro,cityId:city,areaId:area,address:room},
            success: function (data) {
                mccmsa.goTo("complete_add_device","add_device_detail",{id:id});
            }
        })
    })

}
/**
 * Created by Jay on 2016/5/20.
 */
function add_lock() {
    var id=$.bbq.getState("id")||1;
    var check=1;
    var c_id=0;
    var flag=false;
    var first_click=1;

    aa = {
        url:'fsdfdsf',
        data:"fsdf",
    }
    var  aa.url = aa || 1
    $("body").on("mousedown",".open_click",function(e){
        e.stopPropagation();
        console.log(1);
        $(".ishidden").each(function(){
            if($(this).attr("data-click")==c_id){

            }else{
                $(this).slideUp();
            }
        })
        c_id==$(this).attr("data-click")?flag=false:flag=true;
        if(check==1||flag){
            if(flag==true){
                check=0;
            }
            c_id=$(this).attr("data-click");
            $(this).next().stop().removeClass("hidden").slideDown();
            //$(this)..removeClass("hidden").addClass("show");
            check=0;
        }else{
            c_id=$(this).attr("data-click");
            $(this).next().stop().removeClass("hidden").slideUp();
            //$(this).next().removeClass("show").addClass("hidden");
            check=1;
        }
    });
    mccmsa.ajax({
        url: "deviceInfo/getDeviceByCondition",
        data: {pageNo: 1, pageSize: 20,type:0,id:id},
        method: "POST",
        success: function (data){
            console.log(data);
            var use_data=data;
            mccmsa.getHtmlFromLocalTemplate({
                templateId: "add_lock_s",
                container: $("#container_add_lock"),
                data: data,
                callback:function(){
                    $(".append_save").append(" <input class='btn btn-primary radius mt-30 save' type='button' value='保存'>")
                }
            });
            var temp_data=data.result.result.roomNum||2;
            for(var i=0;i<=temp_data;i++){
                $(".lock_detail").children().children().append("<option value="+temp_data[i]+">"+temp_data[i]+"</option>")
            }
            $("body").on("change",".lock_nav",function(){//hidden
                if($(this).val()==0){
                    $(".lock_detail").addClass("hidden");
                }else{
                    $(".lock_detail").addClass("show").removeClass("hidden");
                }
            })

            $("body").on("click",".save",function(){
                var deviceInfos=[];
                for(var i=0;i<$(".container_li").length;i++){
                    deviceInfos[i]={};
                    deviceInfos[i].id=id;
                    deviceInfos[i].deviceType=$(".container_li").eq(i).children(".ishidden").find(".lock_nav").val();
                    deviceInfos[i].roomNum=$(".container_li").children(".ishidden").find(".lock_detail").children().find("select").val();
                }
                 deviceInfos=JSON.stringify(deviceInfos);
                var temp_roomNum=$(".lock_detail").children().children().val()||1;//temp的
                $.ajax({
                    url: "deviceInfo/changeDeviceStatus",
                    data:deviceInfos,
                    method: "POST",
                    success:function(){
                        //跳回原本的
                        mccmsa.goTo("complete_add_lock","add_lock",{id:id})
                    },
                    error:function(){
                        layer.alert("修改失败")
                    }
                })
            })
        }
    })
}
/*添加帐号信息*/
var addUser={};
$("#addUser_form1").validate();//绑定表单1
$("#addUser_form2").validate();//绑定表单2
addUser.bmlock=false;
addUsersubForm=function(){
    if(!$("#addUser_form1").valid()) return;//如果没有就不执行下面的代码
    if(!$("#addUser_form2").valid()) return;//如果没有就不执行下面的代码
    if(addUser.bmlock)return;
    addUser.bmlock=true;
    var userData=$("#addUser_form1").serializeJson();
    userData.companyType=userData.companyType.join(",");
    mccmsa.ajax({
        url:"user/addUser",
        method:"post",
        data:userData,
        dataType:"json",
        success:function(data){
            addUser.bmlock=false;
            if(data.status=='200'){
                $("#username2").val($("#username1").val());
                mccmsa.ajax({
                    url:"contractInfo/addContractInfo",
                    method:"post",
                    data:$("#addUser_form2").serializeJson(),
                    dataType:"json",
                    success:function(data){
                       if(data.status=='200'){
                           layer.msg("提交成功!");
                      }else{
                       }
                    }
                })

            }else{
                addUser.bmlock=false;
            }
        }
    });
};
/*$("#addUser_form1").validate({
    debug:true,//调试模式取消submit的默认提交功能,等ajax验证完之后才提交
    onsubmit:true,// 是否在提交是验证
    onfocusout:false,// 是否在获取焦点时验证
    onkeyup :false,// 是否在敲击键盘时验证
    submitHandler: function(form) {

    },
    errorPlacement: function (error, element) {
       /!* if ($(".mask").html() != "")
            return false;
        $(".mask").html("").show();
        error.appendTo($(".mask"));
        setTimeout(function () {
            $(".mask").empty().fadeOut();
        }, 1000);*!/
    },
    rules: {
        nickName:{
            required:true,
            rangelength:[6,20]
        },
        mobilePhone:{
            required:true,
            moBile:true
        },
        realName:{
            required:true,
            rangelength:[6,20],
            regexName:true
        },
        email:{
            required:true,
            email:true
        },
        companyType:{
            required:true
        }
    },
    messages:{
        nickName:{
            required:"请输入企业名称",
            rangelength:"请输入2-20个字符"
        },
        realName:{
            required:'请输入法人名称',
            rangelength:"请输入2-20个字符",
            regexName:"法人名称只能输入中文"
        },
        mobilePhone:{
            required:"请输入手机号码",
            moBile:"手机号码格式错误"

        },
        email:{
            required:"请输入邮箱",
            email:"邮箱格式错误"
        },
        companyType:{
            required:"请选择企业类型"
        }
    }
});*/



$(function(){
    //头部搜索
    $("#search_text").on("keyup",function(e){
        var search_func=$(this).val();
        var temp_html;
        var temp_href;
        var html_li=" ";
        if(search_func==""){
            $(".search_list").html(" ");
            console.log( $(".search_list").html());
            return;//当搜索input为空时 退出方法
        };
        //ur;"permission/searchPermission",
        mccmsa.ajax({
                 url:"datajson/search.json",
                 type:"POST",
                 data:{likeStr:search_func},
                 success:function(data){
                    // console.log("data:")
                    //console.log(data);
                    for(var i=0;i<data.result.length;i++){
                        temp_href="http://localhost:8080/danbay/index#module=indexCotent&step="+data.result[i].uri;
                        temp_html="<li class='search_li'><a href="+temp_href+">"+data.result[i].name+"</a></li>";
                        html_li=html_li+temp_html;
                   }
                     $(".search_list").html(html_li);
                     html_li=" ";//清空
                     temp_html=" ";//清空
                 }
        });
    })
    //未读消息条数
    //messageInfo/getUnReadByUser
    var message_id=sessionStorage.getItem(id)||1;
    console.log("id",message_id);
    mccmsa.ajax({
        url: "messageInfo/getUnReadByUser?"+ message_id,
        method: "get",
        success:function (data){
          console.log(data);
        }
    });
    // hash改变时跳转到hash对应的页面
    //mccmsa.hashChange
    $(window).on('hashchange',mccmsa.hashChange);
    //绑定返回的方法
    $(document).on('click', '#goBack', function (event) {
        mccmsa.goBack();
    });
    var navContainer = $("#navContainer");

    mccmsa.getHtmlFromRemoteTemplate({
        templateName: "nav.hbs",
        container: navContainer,
        callback: function(){
            $.Huifold("#Huifold .item h4","#Huifold .item .info","fast",1,"click");
        }
    });

    // 点击二级菜单加载内容
    navContainer.on('click', '.ajaxLoad', function (event) {
        var self = $(this);
        // 加载内容
        var rightSrc = self.attr("href");
        var can=rightSrc.substring(rightSrc.indexOf("?"));
        rightSrc=rightSrc.substring(0,rightSrc.indexOf("?"));
        var s=can.length>0 ? can.substring(1) : '';
        if(!s) return null;
        var args={};
        var items=s.split('&');
        var item=null;
        for(var i=0 ;i<items.length;i++){
            item=items[i].split('=');
            args[item[0]]=item[1];
        }
        if (rightSrc != '#') {
            mccmsa.goTo(rightSrc,null,args);
           /* mccmsa.getHtmlFromRemoteTemplate({
                templateName: rightSrc + ".hbs",
                container: $("#mainContainer")
            });*/
        } else {
            alert("略略略略略...");

        }

        // 后添加选中样式
        $(".arrow-r").remove();
        $("li", ".info").removeClass("current");
        self.parent().addClass("current").append('<i class="arrow-r"></i>');
        // 移动端（宽度小于767px）响应式布局时，选择后收起菜单
        if($(window).width()<768){
            $(".Hui-aside").slideToggle();
        }

        return false;
    });

    // 移动端（宽度小于767px）响应式布局头部菜单按钮
    $(".Hui-nav-toggle").click(function(){
        $(".Hui-aside").slideToggle();
    });

    var resizeID;
    /*左侧菜单响应式*/
    $(window).resize(function(){
        clearTimeout(resizeID);
        resizeID = setTimeout(function(){
            if($(window).width()>=768){
                $(".Hui-aside").show()
            }
        }, 300);
    });
    /*hui 选项卡*/
    jQuery.Huitab =function(tabBar,tabCon,class_name,tabEvent,i){
        var $tab_menu=$(tabBar);
        // 初始化操作
        $tab_menu.removeClass(class_name);
        $(tabBar).eq(i).addClass(class_name);
        $(tabCon).hide();
        $(tabCon).eq(i).show();
        $tab_menu.bind(tabEvent,function(){
            $tab_menu.removeClass(class_name);
            $(this).addClass(class_name);
            var index=$tab_menu.index(this);
            $(tabCon).hide();
            $(tabCon).eq(index).show();
        });
    };
    /*hui 选项卡 end*/
});
// 公共方法，定义在mccmsa命名空间下
window.mccmsa = {
    ajax: function(options) {
        var defaultOptions = {
            url: "",
            method: "POST",
            data: {},
            dataType: "json"
        };

        var options = $.extend(defaultOptions, options);

        var loadingLayerIndex;
        return $.ajax({
            url: " " + options.url,
            method: options.method,
            data: options.data,
            dataType: options.dataType,
            beforeSend: function(){
                loadingLayerIndex = layer.load({
                    shade: [0.8, '#393D49']
                });
            },
            success: function(data, xhr){
                if(data.status == 200 || data.status == 300){
                    if(options.success && $.isFunction(options.success)){
                        options.success(data);
                    }
                }else {
                    if(options.success && $.isFunction(options.success)){
                        options.success(data);
                    }
					//alert(data.message)
                    console.log(data.message);
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(textStatus + "[" + jqXHR.status + "]: " + errorThrown);
            },
            complete: function() {
                layer.close(loadingLayerIndex);
            }
        });
    },

    /*
     * 编译服务器端请求的模板并生成Html
     *
     * opt: {
     *   templateName: 模板文件名
     *   container: 模板容器
     *   callback: 模板添加成功后回调
     * }
     * */
    getHtmlFromRemoteTemplate: function(opt){
        var templatePath = "templates/";

        $.ajax({
            url: templatePath + opt.templateName,
            method: "GET",
            success: function(tmpl){
                var template = Handlebars.compile(tmpl);
                opt.container && opt.container.html(template(opt.data || {}));

                if(opt.callback && $.isFunction(opt.callback)){
                    opt.callback();
                }
            },
            error: function(jqXHR, textStatus, errorThrown){
                console.log(textStatus + "[" + jqXHR.status + "]: " + errorThrown);
            }
        });
    },

    /*
     * 编译页面上的模板并生成Html
     *
     * opt: {
     *   templateId: 模板Id
     *   container: 模板容器
     *   callback: 模板添加成功后回调
     * }
     * */
    getHtmlFromLocalTemplate: function(opt){
    	if(opt.data===null){opt.data=''}
    	
        if(opt.templateId && $("#" + opt.templateId).length > 0){

            var template = Handlebars.compile($("#" + opt.templateId).html());
            opt.container && opt.container.html(template(opt.data));

            if(opt.callback && $.isFunction(opt.callback)){
                opt.callback();
            }
        }

    },
//check all
checkAll : function(){
        $(document).on('click', 'input.checkbox',function(event) {
            var flag = true;
            var checkall = $('input.checkbox')[0];
            var that = $(this)[0];
            if(that == checkall){
                flag = that.checked;
                $('input.checkbox').each(function(index, el) {
                    $(this)[0].checked = flag;
                })
            }else{
                $('input.checkbox').each(function(index, el) {
                    //如果有一个没有按得话，就checkall==false，else==true
                    if($(this)[0] != checkall) flag =($(this)[0].checked == false) ? false : flag;
                })
                checkall.checked = flag
            }
        });
    },
    /*
     *对选中的列表进行操作
     *msg.flag : true弹层提示,默认为false，无提示
     *msg.name : 操作名称，不需要弹层可不传
     *msg.url : 操作对应的接口
     *msg.method : 不传入默认为get
     *msg.data : 操作需要传递给接口的参数,不写默认为空
     *msg.fn : 刷新列表的方法
     */
    operation : function(msg,suc,fail){
        msg.method = msg.method || "GET";
        msg.flag = msg.flag || false;
        msg.name = msg.name || '';
        msg.data = msg.data || '';
        msg.check_ids=msg.check_ids||'';
        //console.log("cccc")
        //console.log(msg.check_ids);
        if(msg.flag){
            if (msg.data&&msg.check_ids){
                layer.confirm('确定要'+msg.name+'吗？',{
                    time: 0
                    ,btn: ['确定','取消']
                    ,yes: function(index){
                        layer.close(index);
                        mccmsa.ajax({
                            suc();
                            url: msg.url,
                            method: msg.method,
                            data: msg.data,
                            success: function(){
                                cb()
                                if($('input.checkbox')[0]) $('input.checkbox')[0].checked = false;
                                //msg.fn();
                            }
                        });
                        console.log("yes");
                    }
                });
            }else{
                layer.open({
                    type: 1, //page层
                    area: ['220px', '140px'],
                    title: '提示',
                    btn:"ok",
                    shade: 0.5, //遮罩透明度
                    moveType: 1, //拖拽风格，0是默认，1是传统拖动
                    shift: 0, //0-6的动画形式，-1不开启
                    content: '<div style="padding:10px 22px;">请先选择需要'+msg.name+'的用户</div>'
                });
            }
        }else{
            mccmsa.ajax({
                url: msg.url,
                method: msg.method,
                data: msg.data,
                success: function(){
                    $('input.checkbox')[0].checked = false
                    msg.fn()
                }
            });
        }
    },

    //返回上一级
    goBack: function() {
        if ($('#mainContainer'))$('#mainContainer').off();
        window.history.back();
    },
    /*
     * 调用bbq插件修改url触发页面内容跳转
     *
     * step：步骤名
     * module：模块名
     * params：跳转需要带上的参数
     * */
    goTo: function(step, module, params) {
        var defaultParams = {
            module: module || 'indexCotent',
            step: step || 'indexCotent'
        };
        $.bbq.pushState(
            $.extend(defaultParams, params),
            2
        );
    },
    //hashChange时跳转
    hashChange: function() {
        if ($('#mainContainer'))$('#mainContainer').off();
        // 刷新页面时，如果有模块、步骤信息，显示该模块
        var module = $.bbq.getState('module');
        var step = $.bbq.getState('step');
        if (module && step) {
            // 页面内容“跳转”
            mccmsa.getHtmlFromRemoteTemplate({
                templateName: step+".hbs",
                container: $('#mainContainer'),
                callback: function () {
                }
            });
        }
    }
};
//是否是循环中的第一个helper
var increase=0;//isFirst
Handlebars.registerHelper ("isFirst", function (value, options) {
    increase++;
   if(increase==1||increase<=2){//只能当第一次循环中是两个需要时用
       return options.fn(this);
   }else {
       return options.inverse(this);//else
   }
});
//设备信息
Handlebars.registerHelper ("deviceinfo", function (options) {
    var check_bbq=$.bbq.getState("device_w");
    if(check_bbq==1){//==1就是中控管理
     return "中控网关";
    }else{
        return options.inverse(this);
    }
});
// 相加
Handlebars.registerHelper ("mccmsaAdd", function (value1, value2) {
    return value1 + value2;
});
//时间格式化
Handlebars.registerHelper ("fmtDate", function (timeStamp,fmt) {
    if(typeof(fmt)=="string"){

    }else{
        fmt='yyyy-MM-dd hh:mm:ss';
    }
    var dateStr=new Date(parseInt(timeStamp)).format('yyyy-MM-dd hh:mm:ss');
    return dateStr;
});

//相减
Handlebars.registerHelper ("mccmsaReduce", function (value1, value2) {
    if(isNaN(value1 - value2)){
        return "undefined";
    }
    return value1 - value2;
});

// 粗体
Handlebars.registerHelper ("mccmsaBold", function (value) {
    return new Handlebars.SafeString("<b>" + value + "</b>");
});

// 相等则显示
Handlebars.registerHelper ("mccmsaShowIfEqual", function (value, value2, options) {
    if(value == value2){
        return options.fn(this);
    }
    return options.inverse(this);
});

// 与if使用错误则继续
Handlebars.registerHelper ("error", function (value , options) {
    if(value == ""||value == null){
        return options.fn(this);
    }
});
// 相等则显示
Handlebars.registerHelper ("mccmsaShowIfEqual", function (value, value2, options) {
    if(value == value2){
        return options.fn(this);
    }
    return options.inverse(this);
});
Handlebars.registerHelper ("showIfEqual", function (value, value2, options) {
    if(value == value2){
        return options;
    }

    return "";
});
//判断
Handlebars.registerHelper ("judge", function (value2, options) {
    if(value == value2){
        return options.fn(this);
    }
    return options.inverse(this);
});
/* Jquery plugin START */
/*
* 表单验证，通过给需要验证的输入控件（input、select等）添加类实现验证规则设定
*
* 类名格式：mccms-validate-验证规则[?参数]
* 如：
* 非空 mccms-validate-required
* 最大长度10字符 mccms-validate-maxlength?10
* 输入值大于1小于10范围内 mccms-validate-range?[1,10]
* */
$.validator.messages={
       required: "这里不能为空",
        remote: "Please fix this field.",
        email: "Please enter a valid email address.",
        url: "Please enter a valid URL.",
        date: "Please enter a valid date.",
        dateISO: "Please enter a valid date ( ISO ).",
        number: "Please enter a valid number.",
        digits: "Please enter only digits.",
        creditcard: "Please enter a valid credit card number.",
        equalTo: "两次输入的密码不相等"
}
//[a-z|A-Z|0-9|_]
//jQuery.validator.addMethod("safe_pwd",function(value,element){
//    var tel =/^[a-z|A-Z|0-9]{6,20}&/;
//    return this.optional(element) || (tel.test(value));
//},"请输入6-20位的密码，只包括下划线、英文、数字");//zhongwen

//function validate_t(form_id){
//    form_id=" "||"form_id";
//    jQuery.validator.addMethod("e_mail",function(value,element){
//        var tel = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;//邮箱
//        return this.optional(element) || (tel.test(value));
//    },"请输入正确的真实姓名");//zhongwen
//    jQuery.validator.addMethod("character",function(value,element){
//        var tel = /^[\u4e00-\u9fa5]+$/;//中文
//        return this.optional(element) || (tel.test(value));
//    },"请输入正确的真实姓名");//zhongwen
//    jQuery.validator.addMethod("username",function(value,element){
//        var username = /^[a-zA-Z]{0,9}$/;//username英文
//        return this.optional(element) || (tel.test(value));
//    },"请输入正确的真实姓名");//zhongwen
//    jQuery.validator.addMethod("isMobile",function(value,element){
//        //支持13 15 17 18开头,同时支持xxx-xxxx-xxxx格式手机输入
//        var mobile = /^1[3,5,7,8]\d{9}$|13\d{1}-\d{4}-\d{4}$|15\d{1}-\d{4}-\d{4}$|17\d{1}-\d{4}-\d{4}$|18\d{1}-\d{4}-\d{4}$/;
//        return this.optional(element) || (mobile.test(value));
//    },"请填写正确的手机号码");
//
//    $(form_id).validate({
//        rules:{
//            dizhi:{
//                required: true,
//                character: true
//            },
//            username:{
//                required: true,
//                character: true,
//                rangelength: [2,4]
//            },
//            mobile:{
//                required:true,
//                isMobile:true
//            },
//            email:{
//                required:true,
//                e_mail:true
//            }
//
//        },
//        messages:{
//            dizhi:{
//                required: "请输入地址 ",
//                character:"请输入地址",
//            },
//            username:{
//                required: "请输入正确的真实姓名 ",
//                character:"请输入正确的真实姓名",
//            },
//            userphone:{
//                required: "请输入您的联系地址",
//            },
//            mobile:{
//                required:"请输入您的手机号码",
//                isMobile:"请填写正确的手机号码"
//            },
//            email:{
//                required:"请输入您的邮箱",
//                e_mail:"请输入正确的邮箱"
//            }
//        }
//    });
//};

$.fn.mcFormValide = function(options) {
    var defaultOptions = {};
    options = $.extend(defaultOptions, options);

    return this.each(function(){
        var self = $(this);

        // 需要验证的空间元素，包含mccms-validate-*类的空间元素
        var inputEles = self.find('[class*="mccms-validate-"]');

        var rules = {};
        for(var i = 0; i < inputEles.length; i++){
            var inputEle = inputEles.eq(i);
            var inputClassList = inputEles[i].classList;

            var rule = {};
            var regExpPrefix = /^mccms-validate-/;  // 前缀
            var regExpSuffix = /\?\S+$/;  // 后缀
            for(var j = 0; j < inputClassList.length; j++){
                var clazz = inputClassList[j];

                var ruleName = clazz.replace(regExpPrefix, '').replace(regExpSuffix, "");

                if(regExpPrefix.test(clazz)){
                    // 规则带参数
                    if(regExpSuffix.test(clazz)){
                        rule[ruleName] = clazz.match(regExpSuffix)[0].replace("?", "");  // 把”？“去掉
                    }
                    // 不带参数直接给true
                    else{
                        rule[ruleName] = true;
                    }
                }
            }

            rules[inputEle.attr('name')] = rule;
        }

        self.validate({
            rules: rules
        });
    });
};
/* Jquery plugin END */
var httpUrl = ""
/*alex*/
/*-- nav --*/
function navMenu(){
	mccmsa.ajax({
		url:httpUrl+"permission/menu", 
		method:"GET",
		success:function(json){
			var data=[];
			var temp=[];
			for(var i in json.result){
				if(json.result[i].permissionId==0){
					json.result[i].child=[];
					data.push(json.result[i]);
				}else{
					temp.push(json.result[i]);
				}
			}
			for(var j in temp){
				for(var a in data){
					if(temp[j].permissionId==data[a].id){
						data[a].child.push(temp[j]);
					}
				}
			}
			for (var a = 0;a<data.length;a++) {
				for (var b = 0; b < data.length-a-1; b++){
					if(data[b].id>data[b+1].id){
						var temp=parseInt(data[b].id);
						data[b].id = parseInt(data[b+1].id);
						data[b+1].id = temp;
					}
				}
			}
			var json={};
			json.data=data;
			mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
				templateId: "navMenu",
				container: $("#navContainer"),
				data:json,
				callback: function(){
					$.Huifold("#Huifold .item h4","#Huifold .item .info","fast",1,"click");
				}
			});
			var styleIcon = [];
			$(".item-icon").each(function(){
					if(!styleIcon.length){styleIcon=["basic-setting","ui-style","column-setting ","content-manager","interaction-manager","system-data","system-config"]}
					var random = parseInt(Math.random()*styleIcon.length)
					$(this).addClass(styleIcon[random]);
					styleIcon.splice(random,1);
			})
		}
	})
}

/*
/!*--用户管理--*!/
//列表
function userManage(pageNo){
        //给栏目表录入数据
		if(!pageNo){pageNo=1}		//分页页数
        mccmsa.ajax({
            url:httpUrl+"user/getUserAll",
            method:"GET",
			data:{
				pageNo:pageNo,
				pageSize:8
			},
            success:function(json){
            	for(var i in json.result.resultList){
            		json.result.resultList[i].status=returnStatusCon(json.result.resultList[i].status);
            	}
            	Handlebars.registerHelper("addOne",function(index,options){
					   return parseInt(index)+1+(json.result.pageNo-1)*json.result.pageSize;
				});
                mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                    templateId: "navMain",
                    container: $("#pathContainer")
                });

                mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                    templateId: "getColumnTableData",
                    container: $("#ColumnTableData"),
                    data:json
                });
				pageHtml(json);		//生成分页
                $("#userManage").show();
                $("#onClickDataTable").hide();

                var scrollbarWidth = $('.table-maxHeight')[0].offsetWidth - $('.table-maxHeight')[0].scrollWidth;
                $("table:eq(0)").css("paddingRight",scrollbarWidth);    //获取滚动条宽度并赋值到表头padding-right，对齐
            }
        })
}*/
//查看
function checkData(obj){//查询数据内容框     
        mccmsa.ajax({
                url:httpUrl+"user/getUser/"+$(obj).parents("tr").find("td:first").attr("userId"), //需要添加参数，看接口需要
                method:"GET",
                success:function(data){
                    mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                        templateId: "navCheck",
                        container: $("#pathContainer")
                    });
                    mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                        templateId: "getCheckData",
                        container: $("#onClickDataTable"),
                        data:data
                    });
                    $("#userManage").hide();
                    $("#onClickDataTable").show();
                }
        })
}
//编辑
function editData(obj){//编辑数据内容框
	var id = $(obj).parents("tr").find("td:first").attr("userId");
    mccmsa.ajax({
        url:httpUrl+"user/editUser/"+$(obj).parents("tr").find("td:first").attr("userId"), //需要添加参数，看接口需要
        method:"GET",
        success:function(json){
            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navEdit",
                container: $("#pathContainer")
            });
            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getEditData",
                container: $("#onClickDataTable"),
                data:json
            });
            $("#userManage").hide();
            $("#onClickDataTable").show();
			$("#select option[value='"+json.result.user.status+"']").attr("selected","selected");
			if(json.result.user.roles[0]){
				$("#role input[type=checkbox]:eq("+parseInt(json.result.user.roles[0].id-1)+")").prop("checked", true);
			}
			$("#onClickDataTable tr:first").attr({
				"id":id
			});
        }
    })
}
function postEditData(obj){
	mccmsa.ajax({
        url:httpUrl+"user/updateUserInfo/", //需要添加参数，看接口需要
        method:"POST",
		data:{
			"id":$("#onClickDataTable tr:first").attr("id"),
			"username":$("#username").val(),
			"nickName":$("#nickName").val(),
			"mobilePhone":$("#mobilePhone").val(),
			"roleId":$("#role input[type=checkbox]:checked").val(),
			"status":$("#select option:selected").val()
		},
        success:function(json){
			alert("提交成功")
        } 
    })
}


//密码
function setPassword(obj){//修改密码内容框
		var id = $(obj).parents("tr").find("td:first").attr("userId");
		var userName = $(obj).parents("tr").find("td:eq(1)").text();
		mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
			templateId: "navSetPassword",
			container: $("#pathContainer")
		});
		mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
			templateId: "getSetPassword",
			container: $("#onClickDataTable"),
		});
		$("#onClickDataTable tr:first").attr({
			"id":id,
			"userName":userName
		});
		$("#userManage").hide();
		$("#onClickDataTable").show();
}
function postPassword(obj){//提交修改密码内容框
		mccmsa.ajax({
			url:httpUrl+"user/updateUserSafe", //需要添加参数，看接口需要
			method:"POST",
			data:{
				"id":$("#onClickDataTable tr:first").attr("id"),
				"username":$("#onClickDataTable tr:first").attr("userName"),
				"password":$("#userPassword").val(),
				"authPassword":$("#newPassword").val()
			},
			success:function(json){
				$("#pathContainer input").click();
			}
		})
}


//新增
function newData(obj){//新增数据
		mccmsa.ajax({
			url:httpUrl+"role/getRoleAll", //需要添加参数，看接口需要
			method:"GET",
			success:function(json){
				
				mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
					templateId: "navNewData",
					container: $("#pathContainer")
				});
				mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
					templateId: "getNewData",
					container: $("#onClickDataTable"),
					data:json
				});

				$("#userManage").hide();
				$("#onClickDataTable").show();
			}
		})
		
}
function postNewData(obj){
	mccmsa.ajax({
        url:httpUrl+"user/addUser", //需要添加参数，看接口需要
        method:"POST",
		data:{
			"username":$("#newUserName").val(),
			"password":$("#newPassWord").val(),
			"nickName":$("#newName").val(),
			"mobilePhone":$("#newPhone").val(),
			"roleId":$("#role input:checked").val(),
			"static":$("#select option:selected").val()
		},
        success:function(json){
        	alert(json.message)
            $("#pathContainer input").click();
        }
    })
}
function modalUser(obj){
	$("#myModal").attr("userId",$(obj).parents("tr").find("td:first").attr("userId"));
}
function deleteUser(){
	mccmsa.ajax({
		url:httpUrl+"user/delUser/"+$("#myModal").attr("userId"), //需要添加参数，看接口需要
		method:"POST",
		data:{
			"_method":"delete"
		},
		success:function(json){
			$("#myModal .close").click();
			userManage();
		}
	})
}


/*--角色管理--*/
//列表
function roleManagement(){
    //给栏目表录入数据
    mccmsa.ajax({
        url:httpUrl+"role/getRoleAll",
        method:"GET",
        success:function(json){
            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navMain",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getColumnTableData",
                container: $("#ColumnTableData"),
                data:json
            });

            $("#roleManagement").show();
            $("#onClickDataTable").hide();
			
			pageHtml(json);		//生成分页
			
            var scrollbarWidth = $('.table-maxHeight')[0].offsetWidth - $('.table-maxHeight')[0].scrollWidth;
            $("table:eq(0)").css("paddingRight",scrollbarWidth);    //获取滚动条宽度并赋值到表头padding-right，对齐

            $(".col-7").each(function(){
                    if($(this).text().length>80){
                        var text =  $(this).text().substring(0,80)+"...";
                        $(this).text(text);
                    }
            })

        }
    })
}
//查看
function checkDataRole(obj){
	mccmsa.ajax({
		url:httpUrl+"role/getRole/"+$(obj).parents("tr").attr("getId"), //需要添加参数，看接口需要
		method:"GET",
		success:function(json){
			mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navCheck",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getCheckDataRole",
                container: $("#onClickDataTable"),
                data:json
            });
			$("#roleManagement").hide();
            $("#onClickDataTable").show();
			
		}
	})
}
//编辑
function editDataRole(obj){
	var roleId = $(obj).parents("tr").attr("getId");
	var roleName = $(obj).parents("tr").attr("name");
	mccmsa.ajax({
		url:httpUrl+"role/getRole/"+roleId, //需要添加参数，看接口需要
		method:"GET",
		success:function(json){
			var list=[];
			for(var i=0;i<json.result.permissions.length;i++){
				list.push(json.result.permissions[i].id);
			}
			editDataRoleAll(list,json,roleId,roleName);
		}
	})
}
function editDataRoleAll(list,da,roleId,roleName){
	 //给栏目表录入数据
    mccmsa.ajax({
        url:httpUrl+"permission/getPermissionAll",
        method:"GET",
        success:function(json){
			
            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navEdit",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getEditDataRole",
                container: $("#onClickDataTable"),
                data:da
            });
			for(var i=0;i<json.result.menu.length;i++){
				for(var j=0;j<list.length;j++){
					if(json.result.menu[i].id==list[j]){
						json.result.menu[i].checked=true;
					}
				}
			}
			for(var i=0;i<json.result.front.length;i++){
				for(var j=0;j<list.length;j++){
					if(json.result.front[i].id==list[j]){
						json.result.front[i].checked=true;
					}
				}
			}
			for(var i=0;i<json.result.opt.length;i++){
				for(var j=0;j<list.length;j++){
					if(json.result.opt[i].id==list[j]){
						json.result.opt[i].checked=true;
					}
				}
			}
			
			$("#roleManagement").hide();
            $("#onClickDataTable").show();
			
            var scrollbarWidth = $('.table-maxHeight')[0].offsetWidth - $('.table-maxHeight')[0].scrollWidth;
            $("table:eq(0)").css("paddingRight",scrollbarWidth);    //获取滚动条宽度并赋值到表头padding-right，对齐
			
			var setting = {
				check: {
					enable: true
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					onClick: zTreeOnClick
				}
			};
			
			json.result.menu[json.result.menu.length]={
                "id": 0,
                "permissionType": "0",
                "description": "MCCMS",
				"checked":true,
				open:true
            };
			json.result.front[json.result.front.length]={
                "id": 0,
                "permissionType": "0",
                "description": "MCCMS",
				"checked":true,
				open:true
            };
			$.fn.zTree.init($("#roleMenuTree"), setting, json.result.menu.reverse());
			$.fn.zTree.init($("#roleFrontTree"), setting, json.result.front.reverse());
			
			var data = '';
			for(var i=0;i<json.result.opt.length;i++){
				if(json.result.opt[i].checked){
					data += '<div class="text-l check-box"><input type="checkbox" checked="checked" roleId="'+json.result.opt[i].id+'" id="checkbox-'+i+'"><label for="checkbox-'+i+'">'+json.result.opt[i].description+'</label></div>'
				}else{
					data += '<div class="text-l check-box"><input type="checkbox" roleId="'+json.result.opt[i].id+'" id="checkbox-'+i+'"><label for="checkbox-'+i+'">'+json.result.opt[i].description+'</label></div>'
				}
			}
			$("#roleOptTree").html(data);
			$("#roleId").attr({
				"roleId":roleId,
				"roleName":roleName
			})
			
        }
    })
} 
function postRoleEditData(){
	var list = [];
	var treeFront= $.fn.zTree.getZTreeObj("roleFrontTree");
	var nodesFront = treeFront.getCheckedNodes(true);
	
	
	var treeMenu= $.fn.zTree.getZTreeObj("roleMenuTree");
	var nodesMenu = treeMenu.getCheckedNodes(true);

	for(var i=0;i<nodesFront.length;i++){
		list.push(nodesFront[i].id); //获取每个节点的id
	}
	for(var i=0;i<nodesMenu.length;i++){
		list.push(nodesMenu[i].id); //获取每个节点的id
	}
	
	
	$("#roleOptTree input").each(function(){
		if($(this).is(':checked')){
			list.push($(this).attr("roleid"));
		}
	})
	mccmsa.ajax({
		url:httpUrl+"role/updateRole",
		method:"POST",
		data:{
			id:$("#roleId").attr("roleId"),
			name:$("#roleId").attr("rolename"),
			description:$("#roleDescription").val(),
			permissionss:list.toString()
		},
		success:function(json){
			roleManagement();
		}
	})
	
}
//新增
function roleNewData(){
	var roleId = $("#ColumnTableData tr:first").attr("getId");
	var roleName = $("#ColumnTableData tr:first").attr("name");
	mccmsa.ajax({
		url:httpUrl+"permission/getPermissionAll",
		method:"GET",
		success:function(json){
			 mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navEdit",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getNewDataRole",
                container: $("#onClickDataTable"),
                data:json
            });
			
			$("#roleManagement").hide();
            $("#onClickDataTable").show();
			
			
			var setting = {
				check: {
					enable: true
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					onClick: zTreeOnClick
				}
			};
			
			json.result.menu[json.result.menu.length]={
                "id": 0,
                "permissionType": "0",
                "description": "MCCMS",
				open:true
            };
			json.result.front[json.result.front.length]={
                "id": 0,
                "permissionType": "0",
                "description": "MCCMS",
				open:true
            };
			$.fn.zTree.init($("#roleMenuTree"), setting, json.result.menu.reverse());
			$.fn.zTree.init($("#roleFrontTree"), setting, json.result.front.reverse());
			
			var data = '';
			for(var i=0;i<json.result.opt.length;i++){
				data += '<div class="text-l check-box"><input type="checkbox" roleId="'+json.result.opt[i].id+'" id="checkbox-'+i+'"><label for="checkbox-'+i+'">'+json.result.opt[i].description+'</label></div>'
			}
			$("#roleOptTree").html(data);
			$("#roleId").attr({
				"roleId":roleId,
				"roleName":roleName
			})
		}
	})
	
}
function postRoleNewData(){
	var list = [];
	var treeFront= $.fn.zTree.getZTreeObj("roleFrontTree");
	var nodesFront = treeFront.transformToArray(treeFront.getCheckedNodes(true));
	var treeMenu= $.fn.zTree.getZTreeObj("roleMenuTree");
	var nodesMenu = treeMenu.transformToArray(treeMenu.getCheckedNodes(true));
	
	for(var i=0;i<nodesFront.length;i++){
		list.push(nodesFront[i].id); //获取每个节点的id
	}
	for(var i=0;i<nodesMenu.length;i++){
		list.push(nodesMenu[i].id); //获取每个节点的id
	}
	
	mccmsa.ajax({
		url:httpUrl+"role/addRole",
		method:"POST",
		data:{
			name:$("#roleDescription").val(),
			description:$("#roleDescription").val(),
			permissionss:list.toString()
		},
		success:function(json){
			roleManagement();
		}
	})
}
//删除
function delRoleMode(obj){
	$("#myModal").attr("getId",$(obj).parents("tr").attr("getid"))
}

function postRoleDelData(){
	mccmsa.ajax({
		url:httpUrl+"role/delRole/"+$("#myModal").attr("getId"),
		method:"POST",
		data:{
			"_method":"delete"
		},
		success:function(json){
			roleManagement();
			$("#myModal .close").click();
		}
	})
}

/*--权限管理--*/
//列表
var id;
function permissionManage(){
    //给栏目表录入数据
    mccmsa.ajax({
        url:httpUrl+"permission/getPermissionAll",
        method:"GET",
        success:function(json){
            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navMain",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getColumnTableData",
                container: $("#ColumnTableData"),
                data:json
            });

            $("#permissionManage").show();
            $("#onClickDataTable").hide();
			
            var scrollbarWidth = $('.table-maxHeight')[0].offsetWidth - $('.table-maxHeight')[0].scrollWidth;
            $("table:eq(0)").css("paddingRight",scrollbarWidth);    //获取滚动条宽度并赋值到表头padding-right，对齐
			
			var setting = {                    
				data: {
					simpleData: {
						enable: true,
						idKey: "id"
					},
				},
				callback: {
					onClick: zTreeOnClick
				}
			};
			
			json.result.menu[json.result.menu.length]={
                "id": 0,
                "permissionType": "0",
                "description": "MCCMS",
				open:true
            };
			json.result.front[json.result.front.length]={
                "id": 0,
                "permissionType": "0",
                "description": "MCCMS",
				open:true
            };
			$.fn.zTree.init($("#treeMenu"), setting, json.result.menu.reverse());
			$.fn.zTree.init($("#treeFront"), setting, json.result.front.reverse());
        }
    })
}
//新增
function permissionNewData(obj){//新增数据
		$(".treeFunction").remove();
		mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
			templateId: "navNewData",
			container: $("#pathContainer")
		});
		mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
			templateId: "getNewData",
			container: $("#onClickDataTable"),
		});
		
		$("#parentsZTree .modal-body .modal-treeMenu").html(treeMenu);
		$("#parentsZTree .modal-body .modal-treeFront").html(treeFront);
		
		$("#permissionManage").hide();
		$("#onClickDataTable").show();
}
function newChooseTree(obj){
		if($("#select option:selected").val()==0){
			$("#parentsZTree .modal-body .modal-treeMenu").show();
			$("#parentsZTree .modal-body .modal-treeFront").hide();
		}else if($("#select option:selected").val()==1){
			$("#parentsZTree .modal-body .modal-treeMenu").hide();
			$("#parentsZTree .modal-body .modal-treeFront").show();
		}
}
function postNewPermissionData(){
		mccmsa.ajax({
			url:httpUrl+"permission/addPermission",
			method:"POST",
			data:{
				name:$("#permissionName").val(),
				description:$("#permissionDescription").val(),
				permissionId:id,
				uri:$("#permissionUri").val(),
				permissionType:$("#onClickDataTable #select option:selected").val()
			},
			success:function(json){
				alert(json.message);
				permissionManage();
			}
		})
}
//编辑
function getEditPermissionData(obj){
		var parText = $(obj).parents("ul").prev().find("span:eq(1)").text();
		mccmsa.ajax({
			url:httpUrl+"permission/getPermission/"+id,
			method:"GET",
			success:function(json){
				$(".treeFunction").remove();
				mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
					templateId: "navEdit",
					container: $("#pathContainer")
				});
				mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
					templateId: "getEditData",
					container: $("#onClickDataTable"),
					data:json
				});
				$("#permFirstTr").attr("nodeId",id);
				id = json.result.permissionId;
				$("#parPermission").val(parText);
				$("#select option:eq("+json.result.permissionType+")").attr("selected","selected");
				
				$("#parentsZTree .modal-body .modal-treeMenu").html(treeMenu);
				$("#parentsZTree .modal-body .modal-treeFront").html(treeFront);
				
				$("#permissionManage").hide();
				$("#onClickDataTable").show();
			}
		})
}
function postEditPermissionData(){ 
		mccmsa.ajax({
			url:httpUrl+"permission/updatePermission",
			method:"POST",
			data:{
				id:$("#permFirstTr").attr("nodeId"),
				name:$("#permissionName").val(),
				description:$("#permissionDescription").val(),
				permissionId:id,
				uri:$("#permissionUri").val(),
				permissionType:$("#onClickDataTable #select option:selected").val()
			},
			success:function(json){
				alert(json.message);
				permissionManage();
			}
		})
}
//删除
function postDelPermissionData(){
		mccmsa.ajax({
			url:httpUrl+"permission/delPermission/"+id,
			method:"POST",
			data:{
				"_method":"delete"
			},
			success:function(json){
				alert(json.message);
				permissionManage();
				$(".close").click();
			}
		})
}

function zTreeOnClick(event, treeId, treeNode) {
	id=treeNode.id;
};
function dblClickExpand(treeId, treeNode) {
	return treeNode.level > 0;
};


/*--栏目配置-栏目管理--*/
//列表
function columnClick(){
	$(".Hui-aside a[href=columnConfigTotal]").click();
}
function columnManage(pageNo,id){
        //给栏目表录入数据
		if(!pageNo){pageNo=1}		//分页页数
		if(!id){id=$("#columnManage table").attr("attrId")}
        mccmsa.ajax({
            url:httpUrl+"column/getColumnsSubList/"+id,
            method:"GET",
			data:{
				pageNo:pageNo,
				pageSize:8
			},
            success:function(json){
            	for(var i in json.result.resultList){
            		json.result.resultList[i].isShowInNav=returnIsShowInNav(json.result.resultList[i].isShowInNav);
            		json.result.resultList[i].state=returnStatusCon(json.result.resultList[i].state);
            	}
            	Handlebars.registerHelper("addOne",function(index,options){
					   return parseInt(index)+1+(json.result.pageNo-1)*json.result.pageSize;
				});
                mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
					templateId: "navMain",
					container: $("#pathContainer")
				});
                
                mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                    templateId: "getColumnTableData",
                    container: $("#ColumnTableData"),
                    data:json
                });
				pageHtml(json);		//生成分页
                $("#columnManage,.zTreeDemoBackground").show();
                $("#onClickDataTable").hide();
				
				columnZtree();
				$(".zTreeDemoBackground").append(treeDemo)
				
                var scrollbarWidth = $('.table-maxHeight')[0].offsetWidth - $('.table-maxHeight')[0].scrollWidth;
                $("table:eq(0)").css("paddingRight",scrollbarWidth);    //获取滚动条宽度并赋值到表头padding-right，对齐
			}
        })
}
function columnZtree(){		//初始化zTree
	var setting = {
		view: {
			dblClickExpand: dblClickExpand
		},
		data: {
			simpleData: {
				enable: true
			}
		},
		callback:{
			onClick:columnZtreeClick
		}
	};
	var zNodes = [];
	mccmsa.ajax({
		url:httpUrl+"column/getColumnsInfo",
		method:"GET",
		success:function(json){
			var zeroJson = {
				"id": 0,
				"permissionType": "0",
				"description": "MCCMS",
				open:true
			}
			for(var i=0;i<json.result.length;i++){
				var data = {};
				data.id = json.result[i][0];
				data.permissionId = json.result[i][1];
				data.description = json.result[i][2];
				zNodes.push(data)
			}
			zNodes.push(zeroJson)
			$.fn.zTree.init($("#treeDemo"), setting, zNodes);
		}
	})
}
function columnZtreeClick(event, treeId, treeNode){	//节点点击回调事件
	if(!$("#treeDemo").parents(".modal-scrollable").length){
		if(treeNode.children){
			columnManage(1,treeNode.id)
			$("#columnManage table").attr("attrId",treeNode.id);
		}else{
			columnEdit(false,treeNode)
		}
	}
}
//编辑
function columnEdit(obj,treeNode){
		var id,parentName;
		if(!obj){
			id=treeNode.id;
			parentName=treeNode.getParentNode().description;
		}else{
			id=$(obj).parents("tr").attr("columnid");
			parentName=$.fn.zTree.getZTreeObj("treeDemo").getNodeByParam("id", id, null).getParentNode().description;
		}
		mccmsa.ajax({
            url:httpUrl+"column/getColumnTemplate",
            method:"GET",
            success:function(json){
				var html = "";
				for(var i=0;i<json.result.length;i++){
					html+='<option value="'+json.result[i].id+'">'+json.result[i].name+'</option>'
				}
				mccmsa.ajax({
					url:httpUrl+"column/getColumnById/"+id,
					method:"GET",
					success:function(json){
						mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
							templateId: "navEdit",
							container: $("#pathContainer")
						});

						mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
							templateId: "getEditDataColumn",
							container: $("#onClickDataTable"),
							data:json
						});
						$("#postColumnTemplate").html(html);
						
						$("#columnManage,.zTreeDemoBackground").hide();
						$("#onClickDataTable").show();
						
						$("#isShowInNav option[value='"+json.result.isShowInNav+"']").attr("selected","selected");
						$("#columnState option[value='"+json.result.state+"']").attr("selected","selected");
						$("#postColumnTemplate option[value='"+json.result.template+"']").attr("selected","selected");
						
						$("#sureParents").val(parentName);
						
						$("#parentsZTree .modal-body .modal-treeMenu").html(treeDemo);
						
						//实例化编辑器
						//建议使用工厂方法getEditor创建和引用编辑器实例，如果在某个闭包下引用该编辑器，直接调用UE.getEditor('editor')就能拿到相关的实例
						editor = new UE.ui.Editor();
						editor.render("editor");
						//判断ueditor 编辑器是否创建成功
						editor.addListener("ready", function() {
							// editor准备好之后才可以使用
							if(json.result.content!=null){
								editor.setContent(json.result.content);
							}
						});
						$("#onClickDataTable>tr:last").after('<tr><td class="col-1 table-bgc-f5"></td><td class="text-l col-11"> <input class="btn btn-primary radius" onClick="columnPostEdit()" type="submit" value="提交"></td></tr>')
					}
				})
            }
        })
}
function columnPostEdit(){
		mccmsa.ajax({
            url:httpUrl+"column/editColumn/",
            method:"POST",
			data:{
				"id":$("#postColumnId").attr("columnId"),
				"name":$("#postColumnName").val(),
				"content":editor.getContent(),
				"shortName":$("#postColumnShortName").val(),
				"isShowInNav":$("#isShowInNav option:selected").val(),
				"columnKey":$("#postColumnColumnKey").val(),
				"serial":$("#postColumnSerial").val(),
				"template":$("#postColumnTemplate option:selected").val(),
				"link":$("#postColumnLink").val(),
				"parent":$.fn.zTree.getZTreeObj("treeDemo").getNodeByParam("description", $("#sureParents").val(), null).id,
				"state":$("#columnState option:selected").val()
			},
            success:function(json){
				columnManage();
            }
        })
}
//新增数据
function columnNew(){
		mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
			templateId: "navNew",
			container: $("#pathContainer")
		});

		mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
			templateId: "getNewDataColumn",
			container: $("#onClickDataTable")
		});
		$("#parentsZTree .modal-body .modal-treeMenu").html(treeDemo);
		$("#columnManage,.zTreeDemoBackground").hide();
		$("#onClickDataTable").show();
		
		mccmsa.ajax({
            url:httpUrl+"column/getColumnTemplate",
            method:"GET",
            success:function(json){
				var html = "";
				for(var i=0;i<json.result.length;i++){
					html+='<option value="'+json.result[i].id+'">'+json.result[i].name+'</option>'
				}
				$("#postColumnTemplate").html(html);
				//实例化编辑器
				//建议使用工厂方法getEditor创建和引用编辑器实例，如果在某个闭包下引用该编辑器，直接调用UE.getEditor('editor')就能拿到相关的实例
				editor = new UE.ui.Editor();
				editor.render("editor");
				//判断ueditor 编辑器是否创建成功
				$("#onClickDataTable>tr:last").after('<tr><td class="col-1 table-bgc-f5"></td><td class="text-l col-11"> <input class="btn btn-primary radius" onClick="columnPostNew()" type="submit" value="提交"></td></tr>')
			}
		})
}
function columnPostNew(){
		mccmsa.ajax({
            url:httpUrl+"column/newColumn/",
            method:"POST",
			data:{
				"id":$("#postColumnId").attr("columnId"),
				"name":$("#postColumnName").val(),
				"content":editor.getContent(),
				"shortName":$("#postColumnShortName").val(),
				"isShowInNav":$("#isShowInNav option:selected").val(),
				"columnKey":$("#postColumnColumnKey").val(),
				"serial":$("#postColumnSerial").val(),
				"template":$("#postColumnTemplate option:selected").val(),
				"link":$("#postColumnLink").val(),
				"parent":$.fn.zTree.getZTreeObj("treeDemo").getNodeByParam("description", $("#sureParents").val(), null).id,
				"state":$("#columnState option:selected").val()
			},
            success:function(json){
				columnManage();
            }
        })
}
//删除数据
function postDelColumnData(obj){
	
		mccmsa.ajax({
			url:httpUrl+"column/deleteColumn/"+$("#myModal").attr("columnId"),
			method:"POST",
			data:{
				"_method":"delete"
			},
			success:function(json){
				$("#myModal .close").click();
				columnManage();
			}
		})
}
function columnDel(obj){
	$("#myModal").attr("columnId",$(obj).parents("tr").attr("columnid"))
}



/*--栏目配置-内容管理--*/
//列表

var jsonContent;
var columnName;
var columnId;
var editor;
function Content(obj){
	//给栏目表录入数据
	columnName=$(obj).parents("tr").find("td:eq(1)").text();
	columnId=$(obj).parents("tr").attr("columnid");
	mccmsa.ajax({
		url:httpUrl+"news/getNewsSubList/"+columnId,
		method:"GET",
		success:function(json){
			for(var i in json.result.resultList){
        		json.result.resultList[i].editeTime=returnDate(json.result.resultList[i].editeTime);
        		json.result.resultList[i].state=returnStatusCon(json.result.resultList[i].state);
        	}
			Handlebars.registerHelper("addOne",function(index,options){
				   return parseInt(index)+1+(json.result.pageNo-1)*json.result.pageSize;
			});
			mccmsa.getHtmlFromRemoteTemplate({
                templateName:"contentManage.hbs",
                container: $("#mainContainer")
            });
			jsonContent=json;
		}
	})
}
function contentManage(json){
	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
		templateId: "navMain",
		container: $("#pathContainer")
	});

	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
		templateId: "getColumnTableData",
		container: $("#ColumnTableData"),
		data:json
	});
	$("#contentManage").show();
	$("#htmlCheckContent,#onClickDataTable,#commentList").hide();
	pageHtml(json);		//生成分页
}
//编辑
function contentEdit(obj){
	var objId=$(obj).parents("tr").attr("newid");
	mccmsa.ajax({
		url:httpUrl+"back/news/getDetailById/"+objId,
		method:"GET",
		success:function(json){
			mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
				templateId: "navEdit",
				container: $("#pathContainer")
			});

			mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
				templateId: "getEditDataContent",
				container: $("#onClickDataTable"),
				data:json
			});
			
			$("#onClickDataTable tr:first").attr("newId",$(obj).parents("tr").attr("newid"));
			
			$("#newColumnContent").val(columnName);
			$("#postContentTime").val(returnDate(json.result.createTime));
			$("#postContentUserIntroduction").val(json.result.userIntroduction);
			$("#postContentLike").val(json.result.likeCount);
			$("#postContentClick").val(json.result.clickCount);
			$("#postContentComment").val(json.result.commentCount);
			$("#postContentFavorite").val(json.result.favoriteCount);
			$("#postContentNickname").val(json.result.userNickname);
			$("#postContentBlock").val(json.result.clumnName);
			
			$("#postContentPhoto").attr("src",json.result.userImage);
			
			$("#postContentTitle").val(json.result.title);
			$("#postContentURL").val(json.result.otherURL);
			$("#postContentKey").val(json.result.priKey);
			$("#postContentShortMeta").text(json.result.shortMeta);
			$("#postContentAutor").val(json.result.autor);
			$("#postContentSource").val(json.result.source);
			
			if(json.result.photoFileName!=null){
				$("#preview").attr("src","upload/enterprice/image/"+json.result.photoFileName);
				$("#preview").parent().find(".shadeFile").html(json.result.photoFileName.substring(json.result.photoFileName.lastIndexOf("/")+1))
			}
			
			if(json.result.fileName!=null){
				$("#file").attr("src",json.result.fileName)
				$("#file").parent().find(".shadeFile").html(json.result.fileName.substring(json.result.fileName.lastIndexOf("/")+1))
			}
			
			$(".select option[value="+json.result.state+"]").attr("selected","selected");
			
			
			var jsonObj=[
				$("#postContentIsTop"),json.result.isTop,
				$("#postContentIsCommend"),json.result.isCommend,
				$("#postContentisOnlyContent"),json.result.isOnlyContent,
				$("#postContentIsShowedOnIndex"),json.result.isShowedOnIndex
			];
			checkedObj(jsonObj);
			
			$("#onClickDataTable,#commentList").show();
			$("#htmlCheckContent,#contentManage").hide();
			//实例化编辑器
			//建议使用工厂方法getEditor创建和引用编辑器实例，如果在某个闭包下引用该编辑器，直接调用UE.getEditor('editor')就能拿到相关的实例
			editor = new UE.ui.Editor();
			editor.render("editor");
			//判断ueditor 编辑器是否创建成功
			editor.addListener("ready", function() {
				// editor准备好之后才可以使用
				editor.setContent(json.result.contents);
			});
			$("#onClickDataTable>tr:last").after('<tr><td class="col-1 table-bgc-f5"></td><td class="text-l col-11"> <input class="btn btn-primary radius"  onClick="contentEditPost()" type="submit" value="提交"></td></tr>')
			
			
			mccmsa.ajax({
				url:httpUrl+"back/news/comment/getByNewsId/"+objId,
				method:"GET",
				success:function(json){
					for(var i in json.result.resultList){
							json.result.resultList[i].createTime=returnDate(json.result.resultList[i].createTime);
					}
					mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
						templateId: "getCommentCount",
						container: $("#commentList"),
						data:json
					});
					
					$("#commentList tr:last").after('<tr class="text-c"><td colspan="2"><a href="javascript:" onClick="moreComment(this)" pageNo="'+json.result.pageNo+'">查看更多...</a></td></tr>')
				}
			})
			
		}
	})
}
function contentEditPost(){
	mccmsa.ajax({
		url: httpUrl+"news/editNews",
		method:"POST",
		data:{
			id:$("#onClickDataTable tr:first").attr("newId"),
			columnId:columnId,
			title:$("#postContentTitle").val(),
			priKey:$("#postContentKey").val(),
			shortMeta:$("#postContentShortMeta").val(),
			autor:$("#postContentAutor").val(),
			source:$("#postContentSource").val(),
			contents:editor.getContent(),
			otherURL:$("#postContentURL").val(),
			isTop:$("#postContentIsTop:checked").length?1:0,
			isCommend:$("#postContentIsCommend:checked").length?1:0,
			isOnlyContent:$("#postContentisOnlyContent:checked").length?1:0,
			isShowedOnIndex:$("#postContentIsShowedOnIndex:checked").length?1:0,
			newsType:0,
			fileName:$("#file").attr("src"),
			photoFileName:$("#preview").attr("src").substring($("#preview").attr("src").lastIndexOf("/")+1),
			state:$(".select option:selected").val()
		},
		success:function(json){
			alert(json.message)
			$(".breadcrumb input").click();
		}
	})
	
}
function checkedObj(obj){
	for(var i=0;i<obj.length;i++){
		if(obj[i+1]==1){
			obj[i].attr("checked","checked");
		}
		i++;
	}
}

//评论更多
function moreComment(obj){
	var objId = $("#onClickDataTable>tr:eq(0)").attr("newid");
	mccmsa.ajax({
		url:httpUrl+"back/news/comment/getByNewsId/"+30+"?pageNo="+(parseInt($(obj).attr("pageNo"))+1),//objId,
		method:"GET",
		success:function(json){
			if(json.status==200){
				$(obj).attr("pageNo",json.result.pageNo);
				for(var i in json.result.resultList){
						json.result.resultList[i].createTime=returnDate(json.result.resultList[i].createTime);
				}
				mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
					templateId: "getCommentCount",
					container: $(".listTr"),
					data:json
				});
				$("#commentList tr:last").before($(".listTr").html())
			}else{
				alert(json.message);
			}
		}
	})
}

function comDel(obj){
	mccmsa.ajax({
		url:httpUrl+"back/news/comment/delCom/"+$(obj).attr("comId"),
		method:"DELETE",
		success:function(json){
			alert(json.message);
			$(obj).parents("tr").remove();
		}
	})
	
}

//新增
function contentNew(obj){
	//给栏目表录入数据
	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
		templateId: "navNew",
		container: $("#pathContainer")
	});

	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
		templateId: "getNewDataContent",
		container: $("#onClickDataTable")
	});
	
	$("#newColumnContent").val(columnName);
	
	$("#onClickDataTable").show();
	$("#htmlCheckContent,#contentManage,#commentList").hide();
	
	var scrollbarWidth = $('.table-maxHeight')[0].offsetWidth - $('.table-maxHeight')[0].scrollWidth;
	$("table:eq(0)").css("paddingRight",scrollbarWidth);    //获取滚动条宽度并赋值到表头padding-right，对齐
	//实例化编辑器
	//建议使用工厂方法getEditor创建和引用编辑器实例，如果在某个闭包下引用该编辑器，直接调用UE.getEditor('editor')就能拿到相关的实例
    editor = new UE.ui.Editor();
    editor.render("editor");
	$("#onClickDataTable>tr:last").after('<tr><td class="col-1 table-bgc-f5"></td><td class="text-l col-11"> <input class="btn btn-primary radius"  onClick="contentNewPost()" type="submit" value="提交"></td></tr>');
}

function uploadPhoto(obj){
	if($("#preview").parent().find("img").length==2){
		$(".loadImg").show();
	}else{
		$("#preview").after("<img class='loadImg' src='img/loadFile.gif'>")
	}
	var val = $("#doc").val();
	$.ajaxFileUpload({
		url: httpUrl+"base/imageUpload", //用于文件上传的服务器端请求地址
		secureuri: false, //一般设置为false
		fileElementId: ['doc'], //文件上传空间的id属性  <input type="file" id="file" name="file" />
		dataType: 'json', //返回值类型 一般设置为json

		success: function (data, status){  //服务器成功响应处理函数
			$("#preview").parent().find("span").text(val);
			$("#preview").attr({
				"src":httpUrl.substring(0,httpUrl.length-1)+data.result.substring(1)
			});
			$(".loadImg").hide();
		},
		error: function (data, status, e){//服务器响应失败处理函数
			alert(data.message)
		}
	})
}

function companyLogUploadPhoto(obj){
	if($("#companyLog").parent().find("img").length==2){
		$(".loadImg").show();
	}else{
		$("#companyLog").after("<img class='loadImg' src='img/loadFile.gif'>")
	}
	var val = $("#logo").val();
	$.ajaxFileUpload({
		url: httpUrl+"base/imageUpload", //用于文件上传的服务器端请求地址
		secureuri: false, //一般设置为false
		fileElementId: ['logo'], //文件上传空间的id属性  <input type="file" id="file" name="file" />
		dataType: 'json', //返回值类型 一般设置为json

		success: function (data, status){  //服务器成功响应处理函数
			$("#companyLog").parent().find("span").text(val);
			$("#companyLog").attr({
				"src":httpUrl.substring(0,httpUrl.length-1)+data.result.substring(1)
			});
			$(".loadImg").hide();
		},
		error: function (data, status, e){//服务器响应失败处理函数
			alert(data.message)
		}
	})
}

function uploadFile(){
	if($("#file").parent().find("img").length){
		$(".loadImg").show();
	}else{
		$("#file").before("<img class='loadImg' src='img/loadFile.gif'>")
	}
	var val = $("#file").val();
	$.ajaxFileUpload({
		url: httpUrl+"base/fileUpload", //用于文件上传的服务器端请求地址
		secureuri: false, //一般设置为false
		fileElementId: ['file'], //文件上传空间的id属性  <input type="file" id="file" name="file" />
		dataType: 'json', //返回值类型 一般设置为json

		success: function (data, status){  //服务器成功响应处理函数
			$("#file").parent().find("span").text(val);
			$("#file").attr({
				"src":httpUrl+data.result
			});
			$(".loadImg").hide();
		},
		error: function (data, status, e){//服务器响应失败处理函数
			alert(data.message)
		}
	})
}
function uploadFileCheckup(){
	if($("#file").parent().find("img").length){
		$(".loadImg").show();
	}else{
		$("#file").before("<img class='loadImg' src='img/loadFile.gif'>")
	}
	var val = $("#file").val();
	$.ajaxFileUpload({
		url: "admin/report/"+$(".memberNav").attr("comId")+"/upload", //用于文件上传的服务器端请求地址
		secureuri: false, //一般设置为false
		fileElementId: ['file'], //文件上传空间的id属性  <input type="file" id="file" name="file" />
		dataType: 'json', //返回值类型 一般设置为json

		success: function (data, status){  //服务器成功响应处理函数
			alert("上传成功");
			$("#file").parent().find("span").text(val);
			$("#file").parent().find(".shadeFile").attr("path",data.result);
			$("#file").parent().find(".shadeFile").html(data.result.substring(data.result.lastIndexOf("/")+1));
			$(".loadImg").hide();
		},
		error: function (data, status, e){//服务器响应失败处理函数
			alert(data.message)
		}
	})
}
	

function contentNewPost(){
	mccmsa.ajax({
		url: httpUrl+"news/newNews",
		method:"POST",
		data:{
			columnId:columnId,
			editUser:1,
			title:$("#postContentTitle").val(),
			priKey:$("#postContentKey").val(),
			shortMeta:$("#postContentShortMeta").val(),
			autor:$("#postContentAutor").val(),
			source:$("#postContentSource").val(),
			contents:editor.getContent(),
			otherURL:$("#postContentURL").val(),
			isTop:$("#postContentIsTop:checked").length?1:0,
			isCommend:$("#postContentIsCommend:checked").length?1:0,
			isOnlyContent:$("#postContentisOnlyContent:checked").length?1:0,
			isShowedOnIndex:$("#postContentIsShowedOnIndex:checked").length?1:0,
			newsType:0,
			fileName:$("#file").attr("src"),
			photoFileName:$("#preview").attr("src").substring($("#preview").attr("src").lastIndexOf("/")+1),
			state:$(".select option:selected").val()
		},
		success:function(json){
			alert(json.message)
			updateContent();
		}
	})
}
//删除
function postDelContentData(obj){
		mccmsa.ajax({
			url:httpUrl+"news/deleteNews/"+$("#myModal").attr("columnId"),
			method:"POST",
			data:{
				"_method":"delete"
			},
			success:function(json){
				$("#myModal .close").click();
				updateContent();
			}
		})
}
function updateContent(){
	mccmsa.ajax({
		url:httpUrl+"news/getNewsSubList/"+columnId,
		method:"GET",
		success:function(json){
			contentManage(json);
		}
	})
}
function columnConDel(obj){
	$("#myModal").attr("columnId",$(obj).parents("tr").attr("newid"))
}




/*--栏目配置-模板类型管理--*/
//列表
function templateManage(){
	//给栏目表录入数据
	mccmsa.ajax({
		url:httpUrl+"column/getColumnTemplate",
		method:"GET",
		success:function(json){
			Handlebars.registerHelper("addOne",function(index,options){
				   return parseInt(index)+1+(json.result.pageNo-1)*json.result.pageSize;
			});
			mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
				templateId: "navMain",
				container: $("#pathContainer")
			});

			mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
				templateId: "getColumnTableData",
				container: $("#ColumnTableData"),
				data:json
			});
			//pageHtml(json);		//生成分页
			
			$("#templateManage").show();
			$("#onClickDataTable").hide();
			
			var scrollbarWidth = $('.table-maxHeight')[0].offsetWidth - $('.table-maxHeight')[0].scrollWidth;
			$("table:eq(0)").css("paddingRight",scrollbarWidth);    //获取滚动条宽度并赋值到表头padding-right，对齐
		}
	})
}

function templateNewData(){
	//给栏目表录入数据
	mccmsa.ajax({
		url:httpUrl+"column/getColumnTemplate",
		method:"GET",
		success:function(json){
			Handlebars.registerHelper("addOne",function(index,options){
				   return parseInt(index)+1+(json.result.pageNo-1)*json.result.pageSize;
			});
			mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
				templateId: "navMain",
				container: $("#pathContainer")
			});

			mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
				templateId: "getNewDataTemplate",
				container: $("#onClickDataTable"),
				data:json
			});
			//pageHtml(json);		//生成分页
			$("#onClickDataTable").show();
			$("#templateManage").hide();
		}
	})
}

/*--基本配置-公共信息管理--*/
function commonManage(){
	mccmsa.ajax({
		url:httpUrl+"common/getCommonInfo",
		method:"GET",
		success:function(json){
			mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
				templateId: "navMain",
				container: $("#pathContainer")
			});
			mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
				templateId: "getColumnTableData",
				container: $("#onClickDataTable"),
				data:json.result
			});
		}
	})
}

function commonManagePost(){
	mccmsa.ajax({
		url:httpUrl+"common/updateCommonInfo",
		method:"POST",
		data:{
			"id":$("#onClickDataTable>tr:eq(0)").attr("comId"),
			"company":$("#company").val(),
			"companyEn":$("#companyEn").val(),
			"companyBackground":$("#preview").attr("src").substring($("#preview").attr("src").lastIndexOf("/")+1),
			"companyLog":$("#companyLog").attr("src").substring($("#preview").attr("src").lastIndexOf("/")+1),
			"companyAddr":$("#companyAddr").val(),
			"companyPhone":$("#companyPhone").val(),
			"companyEmail":$("#companyEmail").val(),
			"status":"1"
		},
		success:function(json){
			alert(json.message)
		}
	})
}

/*--基本配置-站点管理--*/
function siteManage(){
		mccmsa.ajax({
			url:httpUrl+"site/getWebSite",
			method:"GET",
			success:function(json){
				mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
					templateId: "navMain",
					container: $("#pathContainer")
				});
				mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
					templateId: "mainTableSite",
					container: $("#onClickDataTable"),
					data:json.result
				});
			}
		})
}

function sitePost(){ 
		mccmsa.ajax({
			url:httpUrl+"site/updateWebSite",
			method:"POST",
			data:{
				"id":$("#onClickDataTable tr:eq(0)").attr("siteId"),
				"siteName":$("#siteName").val(),
				"siteTitle":$("#siteTitle").val(),
				"siteKeyword":$("#siteKeyword").val(),
				"siteDomain":$("#siteDomain").val(),
				"sitePort":$("#sitePort").val(),
				"siteCopyright":$("#siteCopyright").val(),
				"siteRecode":$("#siteRecode").val(),
				"siteDescribe":$("#siteDescribe").val(),
				"siteStatus":1,
			},
			success:function(json){
				
			}
		})
}

/*
 * ajax分页
 */
function pageHtml(json,obj){
	if(json&&json.result&&json.result.pageCount){
		var data="";
		if(json.result.pageCount<=6){
			for(var i=1;i<json.result.pageCount+1;i++){
				data+='<a class="pageClick" pageNo='+i+'>'+i+'</a>';
			}
		}else if(json.result.pageNo>json.result.pageCount-3){
			data+='<a class="pageClick" pageNo="1">1</a>... ...';
			for(var i=json.result.pageCount-3;i<=json.result.pageCount;i++){
				data+='<a class="pageClick" pageNo='+i+'>'+i+'</a>';
			}
		}else if(json.result.pageNo<4){
			for(var i=1;i<6;i++){
				data+='<a class="pageClick" pageNo='+i+'>'+i+'</a>';
			}
			data+='...<a class="pageClick" pageNo='+json.result.pageCount+'>'+json.result.pageCount+'</a>';
		}else{
			data+='<a class="pageClick" pageNo="1">1</a>...';
			data+='<a class="pageClick" pageNo='+(json.result.pageNo-2)+'>'+(json.result.pageNo-2)+'</a>';
			data+='<a class="pageClick" pageNo='+(json.result.pageNo-1)+'>'+(json.result.pageNo-1)+'</a>';
			data+='<a class="pageClick" pageNo='+json.result.pageNo+'>'+json.result.pageNo+'</a>';
			data+='<a class="pageClick" pageNo='+(json.result.pageNo+1)+'>'+(json.result.pageNo+1)+'</a>';
			data+='<a class="pageClick" pageNo='+(json.result.pageNo+2)+'>'+(json.result.pageNo+2)+'</a>';
			data+='...<a class="pageClick" pageNo='+json.result.pageCount+'>'+json.result.pageCount+'</a>';
		}
		if(obj){
			obj.html('<table class="pager" pageNo="'+json.result.pageNo+'"><tbody><tr><td width="60%"><span class="btn btn-small" id="pageIndex">首页</span><span class="btn btn-small" id="pagePrev">上一页</span>'+data+'<span class="btn btn-small" id="pageNext">下一页</span><span class="btn btn-small" id="pageLast">尾页</span></td></tr></tbody></table>');
			obj.find("a[pageNo="+json.result.pageNo+"]").addClass("laypage_curr").removeClass("pageClick");
		}else{
			$("#layPage").html('<table class="pager" pageNo="'+json.result.pageNo+'"><tbody><tr><td width="60%"><span class="btn btn-small" id="pageIndex">首页</span><span class="btn btn-small" id="pagePrev">上一页</span>'+data+'<span class="btn btn-small" id="pageNext">下一页</span><span class="btn btn-small" id="pageLast">尾页</span></td></tr></tbody></table>');
			$("#layPage a[pageNo="+json.result.pageNo+"]").addClass("laypage_curr").removeClass("pageClick");
		}
	}
};
//公用方法
function sureParents(obj){
		var text = $("#parentsZTree .curSelectedNode span:eq(1)").text();
		$("#sureParents").val(text);
		$(".modal-header a").click();
}

/*alex end*/





/*--MCGT START--*/
function Mcgt(){
    $('#mcgtSubmitBtn').on('click', function(){
        var data0={};
        for(var i=0,j=0;i<$("#fieldTr input").length;i++){
            var text = $("#fieldTr input:eq("+i+")").val();
            if(text){
                text = text.split("-");
                data0['mcColumns['+j+'].name']=text[0];
                data0['mcColumns['+j+'].type']=text[1];
                data0['mcColumns['+j+'].length']=text[2];
                data0['mcColumns['+j+'].notNull']=text[3];
                data0['mcColumns['+j+'].defaultValue']=text[4];
                data0['mcColumns['+j+'].comment']=text[5];
                j++;
            }
        }
        var projectRootPathVal = $("#projectRootPathInput").val();
        data0['projectRootPath']= /\\$/.test(projectRootPathVal) ? projectRootPathVal : projectRootPathVal + "\\";
        data0['moduleName']=$("#mcgtFieldNameDesc").val();
        data0['moduleNameDesc']=$("#mcgtFieldName").val();
        data0['name']=$("#mcgtTableName").val();
        data0['comment']=$("#mcgtTableNameDesc").val();

        mccmsa.ajax({
            url:"mcgenerate/generate",
            method:"POST",
            dataType:"json",
            data:data0,
            success:function(json){
                alert("提交成功");
                fieldClear();
            }
        })
    });
}
function fieldSure(){
    mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
        templateId: "navMain",
        container: $("#pathContainer")
    });

    $("#userManage").show();
    $("#onClickDataTable").hide();

    var text="";
    $(".input-text", "#myModal").each(function(){
        text+=($(this).val() || "")+"-"
    });
    //text += $("#field-type").val();
    $("#ColumnTableData #fieldTr input:last").val(text);
    $("#ColumnTableData #fieldTr p:last").after('<p><input type="text" class="input-text input-col-3 mb-10 bgTextColoe" disabled="disabled"></p>');
    $("#myModal .close").click();
    fieldClear();
}
function fieldClear(){
    $(".field input").val("");
}
/*--MCGT END--*/


/* Gary START */
/* Template START */
function Template(){
    var pathContainerEle = $("#pathContainer");
    var listContainerEle = $("#listContainer");
    var operationContainerEle = $("#operationContainer");

    mccmsa.getHtmlFromLocalTemplate({
        templateId: "pathMain",
        container: pathContainerEle
    });

    getListData();

    // 当前位置 新增、返回按钮
    pathContainerEle.on("click", ".path-btn", function(){
        var self = $(this);

        // 新增
        if(self.attr("operation") == "new"){
            // 更新当前位置
            mccmsa.getHtmlFromLocalTemplate({
                templateId: "pathNew",
                container: pathContainerEle
            });
            mccmsa.getHtmlFromLocalTemplate({
                templateId: "newTemplate",
                container: operationContainerEle
            });

            listContainerEle.hide();
            operationContainerEle.show();
        }
        // 返回
        else if(self.attr("operation") == "back"){
            backToList();
        }
    });

    // 列表 查看/编辑按钮
    listContainerEle.on("click", ".operation-btn", function(){
        var self = $(this);

        // 查看
        if(self.attr("operation") == "check"){
            mccmsa.ajax({
                url: "jsonData/check",
                data: {}, // 传id？
                method:"GET",
                success:function(data){
                    // 更新当前位置
                    mccmsa.getHtmlFromLocalTemplate({
                        templateId: "pathCheck",
                        container: pathContainerEle
                    });
                    mccmsa.getHtmlFromLocalTemplate({
                        templateId: "editTemplate",
                        container: operationContainerEle,
                        data: data.result
                    });

                    listContainerEle.hide();
                    operationContainerEle.show();
                }
            })
        }
    });

    // 新增/查看/修改提交按钮
    operationContainerEle.on("click", ".operation-submit-btn", function(){
        var self = $(this);

        // 新增提交
        if(self.attr("operation") == "new"){
            mccmsa.ajax({
                url: "jsonData/new", //需要添加参数，看接口需要
                method: "GET",
                data: $("newForm").serialize,
                success:function(json){
                    mccmsa.getHtmlFromLocalTemplate({
                        templateId: "getNewData",
                        container: $("#onClickDataTable"),
                        data:json
                    });

                    getListData();
                    backToList();
                }
            })
        }

        if(self.attr("operation") == "edit"){

        }
    });
}

// 取列表数据，显示列表
function getListData(){
    mccmsa.ajax({
        url: "jsonData/apiUrl",
        method:"GET",
        data:{},
        success:function(data){
            mccmsa.getHtmlFromLocalTemplate({
                templateId: "listTemplate",
                container: $("#listContentContainer"),
                data: data
            });

            pageHtml(data);		//生成分页

            var tableMaxHeightELe = $('.table-maxHeight')[0];
            var scrollbarWidth = tableMaxHeightELe.offsetWidth - tableMaxHeightELe.scrollWidth;
            $("table:eq(0)").css("paddingRight",scrollbarWidth);    //获取滚动条宽度并赋值到表头padding-right，对齐
        }
    });
}

function backToList(){
    mccmsa.getHtmlFromLocalTemplate({
        templateId: "pathMain",
        container: $("#pathContainer")
    });

    $("#listContainer").show();
    $("#operationContainer").hide();
}

/* Template END */
/* Gary END */
/*jerry  start*/
function site() { 
    //添加自定义模块
    $(".select").change(function() {
        var option_val = $(".select option:selected").val(); //获取选中元素的值
        $("#" + option_val).parents(".row").fadeIn(); //显示自定义模块
    });
    //删除自定义模块
    $(".close-icon").on("click", function() {
        $(this).parents(".row").fadeOut();
    })
    mccmsa.ajax({
        url: "jsonData/siteInfo", //需要添加参数，看接口需要
        method: "GET",
        success: function(data) {
            mccmsa.getHtmlFromLocalTemplate({ //将数据打包到模版丢进容器
                templateId: "siteinfo",
                container: $("#form"),
                data: data
            });
        }
    })
}

/*加载互动管理 START*/
function friendly_link() {
    mccmsa.ajax({
        url: 'jsonData/friendly_link',
        method: "GET",
        success: function(data) {
            mccmsa.getHtmlFromLocalTemplate({ //加载导航栏
                templateId: "nav_location",
                container: $("#pathContainer")
            });
            mccmsa.getHtmlFromLocalTemplate({ //加载页面数据
                templateId: "getColumnTableData",
                container: $("#ColumnTableData"),
                data: data
            });
            $("#friendly_link").show();
            $("#onClickDataTable").hide();
            var scrollbarWidth = $('.table-maxHeight')[0].offsetWidth - $('.table-maxHeight')[0].scrollWidth;
            $("table:eq(0)").css("paddingRight", scrollbarWidth); //获取滚动条宽度并赋值到表头padding-right，对齐            
        }
    })
    laypage({
        cont: 'layPage', //容器。值支持id名、原生dom对象，jquery对象,
        pages: 10, //总页数
        skin: 'molv', //皮肤
        first: '首页', //若不显示，设置false即可
        last: '尾页', //若不显示，设置false即可
        prev: '<', //若不显示，设置false即可
        next: '>' //若不显示，设置false即可
    });
}
//新增链接
function new_link() {
    mccmsa.ajax({
        url: 'jsonData/new_friendly_link',
        method: "GET",
        success: function(data) {
            mccmsa.getHtmlFromLocalTemplate({ //加载导航栏
                templateId: "nav_location_return",
                container: $("#pathContainer")
            });
            mccmsa.getHtmlFromLocalTemplate({
                templateId: "new_link",
                container: $("#onClickDataTable"),
                data: data
            });
            $("#onClickDataTable").show();
            $("#friendly_link").hide();
        }
    })
}
//查看链接
function check_link(){
        mccmsa.ajax({
        url: 'jsonData/check_link',
        method: "GET",
        success: function(data) {
            mccmsa.getHtmlFromLocalTemplate({ //加载导航栏
                templateId: "nav_location_return",
                container: $("#pathContainer")
            });
            $("#true_location").text("查看链接");
            mccmsa.getHtmlFromLocalTemplate({
                templateId: "check_link",
                container: $("#onClickDataTable"),
                data: data
            });
            $("#onClickDataTable").show();
            $("#friendly_link").hide();
        }
    })
}

/*加载互动管理 END*/

/*jerry  finshed
/*jerry  start*/
 
function site(){
	$("#submitBtn").click(function(event) {
		event.preventDefault();

		var site = {
			name:$("#name").val(),
			link:$("#link").val(),
			title:$("#title").val(),
			index_name:$("#index_name").val(),
			port:$("#port").val(),
			company:$("#company").val(),
			copyright:$("#copyright").val(),
			icp:$("#icp").val()
		};
		alert(site);
		mccmsa.ajax({
			url: 'http://192.168.31.249:8180/galaxy_pcserver_crm/users/test',
			method: 'GET',
			data:site,
			success:function(data){
				var msg = data.msg;
				alert(msg)
			},
			error:(function() {
				alert("1111")
			})
		})

		
	});


}


/*jerry  finshed*/

function Test(){
    var submitBtn = $("#submitBtn");
 
    init();

    function init(){
        mccmsa.getHtmlFromLocalTemplate({
            templateId: "testLocalTemplate",
            container: $("#pathContainer"),
            data: {
                "path1": "基本配置",
                "path2": "站点配置",
                "array": [
                    {
                        "name": "tina"
                    },
                    {
                        "name": "alex"
                    }
                ]
            }
        });

        submitBtn.on("click", function(){
            alert("submit!");

            return false;
        });
    }

}

    /*单选框控制*/
function iCheck(){
        $('.skin-minimal input').iCheck({
            checkboxClass: 'icheckbox-blue',
            radioClass: 'iradio-blue',
            increaseArea: '20%'
        });
    }
    /*单选框控制*/

$(function(){
	$("body").on("click",".only-checkbox input",function(){
		$(this).parents(".only-checkbox").find("input").prop("checked",false);
		$(this).prop("checked",true);
	})
})

/**
 * Created by Jay on 2016/5/24.
 */
function complete_add_device(){
    var id=$.bbq.getState("id")||1;
    mccmsa.ajax({
        url:"centerControl/getCenterControl/"+id,
        method:"get",
        success: function (data) {
            console.log(data);
            mccmsa.getHtmlFromLocalTemplate({
                templateId: "c_add_device_s",
                container: $("#complete_add_device_cc"),
                data: data,
                callback:function(){
                    $("#complete_add_device_cc").find(".prov").html(data.result.province.province);
                    $("#complete_add_device_cc").find(".city").html(data.result.city.city);
                    $("#complete_add_device_cc").find(".area").html(data.result.area.area);
                    $(".device_name").html(data.result.address);
                    //$("body").on("click","add_address",function(){
                    //    mccmsa.goTo("add_device","complete_add_device",{id:id});
                    //    alert(1);
                    //})
                    $(".add_address").click(function(){
                        mccmsa.goTo("add_device","complete_add_device",{id:id});
                    })
                    $(".btn-primary").click(function(){
                        mccmsa.goTo("add_device","complete_add_device",{id:id});
                    })
                    //$("body").on("click","btn-primary",function(){
                    //    mccmsa.goTo("add_device","complete_add_device");
                    //})
                }
            });

        }
    })
}
/**
 * Created by Jay on 2016/5/27.
 */
function  complete_add_lock(){
    $("body").unbind("click");
    var data_t=0;
    var id=$.bbq.getState("id")||1;
    mccmsa.ajax({
        url: "deviceInfo/getDeviceByCondition",
        data: {pageNo: 1, pageSize: 20,type:0,id:id},
        method: "POST",
        success: function (data){
            mccmsa.getHtmlFromLocalTemplate({
                templateId: "add_lock_s",
                container: $("#container_add_lock"),
                data: data,
                callback:function(){
                    $(".append_save").append(" <input class='btn btn-primary radius mt-30 save' type='button' value='完成'>");
                    $("body").on("click",".save",function(e){
                        e.stopPropagation();
                        mccmsa.goTo("add_lock_t","complete_add_lock");
                    })
                }
            });
            //$(".open_click")
            for(var x=0;x<$(".container_li").length;x++){
                $(".container_li").eq(x).find(".prov").html(data.result.resultList[0].centerControl.province.province);
                $(".container_li").eq(x).find(".city").html(data.result.resultList[0].centerControl.city.city);
                $(".container_li").eq(x).find(".area").html(data.result.resultList[0].centerControl.area.area);
            }
        }
    })
}
/**
 * Created by Jay on 2016/5/24.
 */
function daily_account(){
    $("body").on("click",".search_btn",function(e){
        e.preventDefault();
        //console.log($("#daily_manager_form").serialize());
        var da=$("#daily_manager_form").serialize();
        var bg_t=$("#daily_manager_form input").eq(0).val();
        var end_t=$("#daily_manager_form input").eq(1).val();
        var search=$("#daily_manager_form input").eq(2).val();
        mccmsa.ajax({
            url: "logInfo/getAccountLogInfo",
            method: "post",
            data: {pageNo: "1", pageSize: "10",beginTime:bg_t,endTime:end_t,q:search},
            success:function(data){
                mccmsa.getHtmlFromLocalTemplate({
                    templateId: "daily_manager_c",
                    container: $("#daily_manager_container_c"),
                    data: data,
                    callback:function(){
                    }
                });
                //生成分页
                $("#layPage").createPage({
                    pageCount:data.result.pageCount,
                    current:data.result.pageNo,
                    backFn:function(p){
                        mccmsa.ajax({
                            url:"logInfo/getAccountLogInfo",
                            data:{pageNo:p,pageSize:20,status:3,beginTime:bg_t,endTime:end_t,q:search},
                            method:"POST",
                            success:function(data){
                                mccmsa.getHtmlFromLocalTemplate({
                                    templateId:"getColumnTableData",
                                    container: $("#ColumnTableData"),
                                    data:data
                                });
                            }
                        })
                    }
                });
            }
        })
        return false;
    });
    mccmsa.ajax({
        url:"logInfo/getAccountLogInfo",
        method:"post",
        data:{pageNo:"1",pageSize:"10"},
        success:function(data){
            console.log(data);
            mccmsa.getHtmlFromLocalTemplate({
                templateId: "daily_manager_c",
                container: $("#daily_manager_container_c"),
                data: data,
                callback:function(){

                }
            });
            //生成分页
            $("#layPage").createPage({
                pageCount:data.pageCount,
                current:1,
                backFn:function(p){
                    mccmsa.ajax({
                        url:"datajson/getMessageInfoByCondition.json",
                        data:{pageNo:p,pageSize:20,status:3},
                        method:"POST",
                        success:function(data){
                            mccmsa.getHtmlFromLocalTemplate({
                                templateId:"getColumnTableData",
                                container: $("#ColumnTableData"),
                                data:data
                            });
                        }
                    })
                }
            });
            //$("body"),on("click","#daily_manager_form",function(e){
            //    e.preventDefault();
            //})
        }

    })
}
/**
 * Created by Jay on 2016/5/24.
 */
function daily_manager(){
    $("body").on("click",".search_btn",function(e){
        e.preventDefault();
        //console.log($("#daily_manager_form").serialize());
        var da=$("#daily_manager_form").serialize();
        var bg_t=$("#daily_manager_form input").eq(0).val();
        var end_t=$("#daily_manager_form input").eq(1).val();
        var search=$("#daily_manager_form input").eq(3).val();
        mccmsa.ajax({
            url: "logInfo/getDeviceLogInfo",
            method: "post",
            data: {pageNo: "1", pageSize: "10",beginTime:bg_t,endTime:end_t,q:search},
            success:function(data) {
                mccmsa.getHtmlFromLocalTemplate({
                    templateId: "daily_manager_s",
                    container: $("#daily_manager_container_s"),
                    data: data,
                    callback: function () {
                    }
                });
                //生成分页
                $("#layPage").createPage({
                    pageCount:data.result.pageCount,
                    current:data.result.pageNo,
                    backFn:function(p){
                        mccmsa.ajax({
                            url:"logInfo/getDeviceLogInfo",
                            data:{pageNo:p,pageSize:20,status:3,beginTime:bg_t,endTime:end_t,q:search},
                            method:"POST",
                            success:function(data){
                                mccmsa.getHtmlFromLocalTemplate({
                                    templateId:"getColumnTableData",
                                    container: $("#ColumnTableData"),
                                    data:data
                                });
                            }
                        })
                    }
                });
            }
        })
        return false;
    });//click search


    mccmsa.ajax({
        url:"logInfo/getDeviceLogInfo",
        method:"post",
        data:{pageNo:"1",pageSize:"10"},
        success:function(data){
            console.log(data);
            mccmsa.getHtmlFromLocalTemplate({
                templateId: "daily_manager_s",
                container: $("#daily_manager_container_s"),
                data: data,
                callback:function(){
                }
            });
            //生成分页
            $("#layPage").createPage({
                pageCount:data.result.pageCount,
                current:data.result.pageNo,
                backFn:function(p){
                    mccmsa.ajax({
                        url:"logInfo/getDeviceLogInfo",
                        data:{pageNo:p,pageSize:20,status:3,beginTime:bg_t,endTime:end_t,q:search},
                        method:"POST",
                        success:function(data){
                            mccmsa.getHtmlFromLocalTemplate({
                                templateId:"getColumnTableData",
                                container: $("#ColumnTableData"),
                                data:data
                            });
                        }
                    })
                }
            });
            //$("body"),on("click","#daily_manager_form",function(e){
            //    e.preventDefault();
            //})
        }

    })
}
/**
 * Created by Jay on 2016/5/19.
 */
function  deviceInfoSearch(){
    mccmsa.ajax({
        url:"centerControl/findCenterControl",
        data:{pageNo:1,pageSize:20},
        method:"POST",
        success: function (data) {
                data.result.role=sessionStorage.getItem("role");
                mccmsa.getHtmlFromLocalTemplate({
                    templateId: "deviceListData",
                    container: $("#deviceList"),
                    data: data.result
                });
                //getCity 放入select
                mccmsa.getHtmlFromLocalTemplate({
                    templateId: "getCity",
                    container: $("#eq_header_select"),
                    data: data.result,
                    callback:function(){
                        var str="";
                        for(var i=0;i<province.length;i++){
                            str+="<option value='"+province[i].provinceid+"'>"+province[i].province+"</option>";
                        }
                        $("#province").append(str);
                        initCity();
                    }
                });
                //生成分页
                $("#layPage").createPage({
                    pageCount: data.result.result.pageCount,
                    current: data.result.result.pageNo,
                    backFn: function (p) {
                        mccmsa.ajax({
                            url: "centerControl/findCenterControl",
                            data: {pageNo: p, pageSize: 20},
                            method: "POST",
                            success: function (data) {
                                data.result.role=sessionStorage.getItem("role");
                                mccmsa.getHtmlFromLocalTemplate({
                                    templateId: "deviceListData",
                                    container: $("#deviceList"),
                                    data: data.result
                                });
                            }
                        })
                    }
                });
                //门锁操作
                $("body").on("click",".op_door",function(){
                    //$(this).data();
                    var id=$(this).attr("data-id");
                    //console.log("id="+id);
                    var where=$(this).parents().eq(0).parent().children(".t_hover_c_db").children("a").html();
                    mccmsa.goTo("door_lock","deviceInfoSearch",{id:id,where:where});
                });
                //goTo中控设备信息
                $("body").on("click",".t_hover_c_db",function(e){
                    e.preventDefault();//阻止a的事件触发
                    console.log($(this).children("a").attr("data-id"));
                     var this_id=$(this).children("a").attr("data-id")
                    mccmsa.goTo("deviceInfo_detail","deviceInfoSearch",{device_w:1,id:this_id});
                    return false;
                });
                //选择查询
                $("body").on("change","#deviceSel select",function(){
                    var json=$("#deviceSel").serializeJson();
                    json.pageNo=1;
                    json.pageSize=20;
                    mccmsa.ajax({
                        url:"centerControl/findCenterControl",
                        data:json,
                        method:"POST",
                        success:function(data){
                            data.result.role=sessionStorage.getItem("role");
                            mccmsa.getHtmlFromLocalTemplate({
                                templateId: "deviceListData",
                                container: $("#deviceList"),
                                data: data.result
                            });
                            //生成分页
                            $("#layPage").createPage({
                                pageCount: data.result.result.pageCount,
                                current: data.result.result.pageNo,
                                backFn: function (p) {
                                    json.pageNo=p;
                                    mccmsa.ajax({
                                        url: "centerControl/findCenterControl",
                                        data:json,
                                        method: "POST",
                                        success: function (data) {
                                            data.result.role=sessionStorage.getItem("role");
                                            mccmsa.getHtmlFromLocalTemplate({
                                                templateId: "deviceListData",
                                                container: $("#deviceList"),
                                                data: data.result
                                            });
                                        }
                                    })
                                }
                            });
                        }
                    })
                });
                $("body").on("click","#searchDevice",function(){
                    var json=$("#deviceSel").serializeJson();
                    json.pageNo=1;
                    json.pageSize=20;
                    if(testMac(json.likeStr)){ //搜索mac
                        mccmsa.ajax({
                            url:"centerControl/findCenterControl",
                            data:{pageNo:1,pageSize:20,likeStr:json.likeStr},
                            method:"POST",
                            success:function(data){
                                if(0==data.result.result.resultList.length){
                                    layer.msg("没有对应设备");
                                    return;
                                }
                                var id=data.result.result.resultList[0].id;
                                mccmsa.goTo("door_lock","deviceInfoSearch",{id:id});
                            }
                        });
                        return;
                    }
                    mccmsa.ajax({
                        url:"centerControl/findCenterControl",
                        data:json,
                        method:"POST",
                        success:function(data){
                            data.result.role=sessionStorage.getItem("role");
                            mccmsa.getHtmlFromLocalTemplate({
                                templateId: "deviceListData",
                                container: $("#deviceList"),
                                data: data.result
                            });
                            //生成分页
                            $("#layPage").createPage({
                                pageCount: data.result.result.pageCount,
                                current: data.result.result.pageNo,
                                backFn: function (p) {
                                    json.pageNo=p;
                                    mccmsa.ajax({
                                        url: "centerControl/findCenterControl",
                                        data:json,
                                        method: "POST",
                                        success: function (data) {
                                            data.result.role=sessionStorage.getItem("role");
                                            mccmsa.getHtmlFromLocalTemplate({
                                                templateId: "deviceListData",
                                                container: $("#deviceList"),
                                                data: data.result
                                            });
                                        }
                                    })
                                }
                            });
                        }
                    })
                })
    }
})
}
function testMac(mac){
    mac=mac.trim();
    var exp=/^[A-F0-9]{2}(\:[A-F0-9]{2}){5}$/g;
    return exp.test(mac);
}
function deviceSel(){
    return $("#deviceSel").serializeJson();
}

/**
 * Created by Jay on 2016/5/20.
 */
function deviceInfoSearch_page(){
    var search_mess=$.bbq.getState("search_mess");
    $(".de_search_name").html(search_mess);
    console.log(search_mess);
    mccmsa.ajax({
        url:"centerControl/findCenterControl",
        data:{pageNo:1,pageSize:20,likeStr:search_mess},
        method:"POST",
        success: function (data) {
            console.log(data);
            mccmsa.getHtmlFromLocalTemplate({
                templateId: "getColumnTableData",
                container: $("#ColumnTableData"),
                data: data
            });
        }
    })
}
/**
 * Created by Jay on 2016/5/21.
 */
function deviceInfo_detail(){
    var contract_1="";
    var check=$.bbq.getState("device_w");
    var id=$.bbq.getState("id");
    if(check==1){//中控设备
        mccmsa.ajax({
        url:"centerControl/getCenterControl/"+id,
        method:"get",
        success: function (data) {
            contract_1=data.result.contractInfo.contractNum;
              console.log(data);
            console.log(data.result.status)
              //getColumnTableData
              mccmsa.getHtmlFromLocalTemplate({
                  templateId:"getColumnTableData",
                  container: $("#base_mess"),
                  data:data,
                  callback:function(){
                      //删除中控
                      $(".c-error").click(function(){
                          mccmsa.ajax({
                              url: "centerControl/delCenterControl",
                              method: "POST",
                              data:{id:id},
                              success: function(){
                                  mccmsa.goTo("deviceInfgooSearch","deviceInfo_detail");
                              }
                          })
                      })
                  }
              });
              mccmsa.getHtmlFromLocalTemplate({
                  templateId:"status_mess_in",
                  container: $("#status_mess"),
                  data:data
              });
              mccmsa.getHtmlFromLocalTemplate({
                  templateId:"status_mess_in_d",
                  container: $("#status_mess_in_d_in"),
                  data:data
              });
            //city
            var str="";
            for(var i=0;i<province.length;i++){
                str+="<option value='"+province[i].provinceid+"'>"+province[i].province+"</option>";
            }
            $("#province").append(str);
            initCity();
          }
        })
    }
//   click
    $("body").on("click",".certain_btn",function(){
        var pro=$(".select_city li span").eq(0).children().find("option:selected").val();
        var city=$(".select_city li span").eq(1).children().find("option:selected").val();
        var area=$(".select_city li span").eq(2).children().find("option:selected").val();
        var account=$("#change_address_form input").eq(1).val();
        var room=$("#change_address_form input").eq(0).val();
        mccmsa.ajax({
            url: "centerControl/addCenterControl",
            method: "POST",
            data: {
                id: id,
                username: account,
                contractNum: contract_1,
                provinceId: pro,
                cityId: city,
                areaId: area,
                address: room
            },
            success: function (data) {
            }
        })
    });
    $("body").on("click",".c_a",function(){
        $(".change_name").html($(".eq_address").html());
    })

}
//mccmsa.ajax({
//    url:"centerControl/addCenterControl",
//    method:"POST",
//    data:{id:id,username:account,contractNum:contract_1,provinceId:pro,cityId:city,areaId:area,address:room},
//    success: function (data) {

/**
 * Created by Jay on 2016/5/24.
 */
function  deviceInfo_detail_lock(){
    var w=$.bbq.getState("device_w");
    var id= $.bbq.getState("id");
    //city
    var str="";
    for(var i=0;i<province.length;i++){
        str+="<option value='"+province[i].provinceid+"'>"+province[i].province+"</option>";
    }
    $("#province").append(str);
    initCity();
    $("#change_address_form").validate();//绑定表单
    //city end
    if(w==2){
        mccmsa.ajax({
            url: "deviceInfo/getDeviceInfo/"+id,
            method: "get",
            success: function (data) {
                console.log(data);
                //1
                mccmsa.getHtmlFromLocalTemplate({
                    templateId:"getColumnTableData",
                    container: $("#base_mess"),
                    data:data,
                    callback:function(){
                        //删除设备
                        $(".c-error").click(function(){
                            mccmsa.ajax({
                                url: "deviceInfo/delDeviceInfo",
                                method: "POST",
                                data:{id:id},
                                success: function(){
                                    mccmsa.goTo("deviceInfoSearch","deviceInfo_detail_lock")
                                }
                             })
                        })
                    }
                });
                //2
                mccmsa.getHtmlFromLocalTemplate({
                    templateId:"status_mess_in",
                    container: $("#status_mess"),
                    data:data
                });
                //3
                mccmsa.getHtmlFromLocalTemplate({
                    templateId:"status_mess_in_d",
                    container: $("#status_mess_in_d_in"),
                    data:data,
                    callback: function(){
                        var x=$("#mainContainer").children("div").eq(2).find("#status_mess_in_d_in").children("li").children("ul").find("li");
                        x.eq(1).html("<span class='c-999'>设备标签</span>");
                        x.eq(2).html(" ");
                        x.eq(3).html(" ");
                        $(".certain_btn").on("click",function(){
                            alert(1);
                            var pro=$("#change_address_form select").eq(3).find("option:selected").val();
                            var city= $("#change_address_form select").eq(4).find("option:selected").val();
                            var area=$("#change_address_form select").eq(5).find("option:selected").val();
                            //mccmsa.ajax({
                            //    url: "deviceInfo/getDeviceInfo/" + id,
                            //    method: "get",
                            //    data:
                            //    success: function (data) {
                            //
                            //    }
                            //})
                        })
                    }
                });
            }
        })

    }

}

/**
 * Created by Jay on 2016/5/17.
 */

/*** Created by Jay on 2016/5/23.*/
function door_lock(){
    var where=$.bbq.getState("where");//address 头部的
    var id= $.bbq.getState("id");
        mccmsa.ajax({
            url: "deviceInfo/getDeviceByCondition/",
            data:{id:id,pageNo:1,pageSize:10000},
            method: "POST",
            success:function(data){
                date=data.result.resultList;
                increase=0;//重置isFirst helper
                var tongbu=[];
                for(var i=0;i<data.result.result.resultList.length;i++){
                    if(data.result.result.resultList[i].dataType==1){
                        if(data.result.result.resultList[i].hasSync==1){
                            tongbu.push(data.result.result.resultList[i].roomNum);
                        }
                    }
                }
                data.result.result.tongbu=tongbu.join("/");
                mccmsa.getHtmlFromLocalTemplate({
                    container:$("#ColumnTableData"),
                    templateId:"door_lock_table_data",
                    data:data.result
                });
                $(".room_class").on("click",function(e){
                    var data_id=$(this).attr("data-id");
                    var dw=$(this).attr("data-device_w");
                    //console.log(data_id,dw);
                    e.preventDefault();
                    mccmsa.goTo("deviceInfo_detail_lock","door_lock",{device_w:dw,id:data_id});
                });
                $(".header_mess").html(data.result.name);//address
            }
        })
}
/*操作管家密码*/
function upDatePwdMan(node,type){
    var id=$(node).attr("data-id");
    mccmsa.ajax({
        url:"devicePwdInfo/upDatePwds",
        method:"post",
        data:{id:id,type:type,pwdType:2},
        success:function(data){
            if(200==data.status){
                var parent=$(node).parent();
                $(node).remove();
                if(1==type){
                    layer.msg("启用指令已发送");
                    mccmsa.hashChange();
                    //parent.append('<span class="btn btn-primary radius" data-id="'+id+'" onclick="upDatePwdMan(this,0)">冻结</span>');
                }else if(2==type){
                    layer.msg("冻结指令已发送");
                    mccmsa.hashChange();
                    //parent.append('<span class="btn btn-warning-outline radius" data-id="'+id+'" onclick="upDatePwdMan(this,1)">启用</span>');
                }
            }
        }
    })
}
/*操作用户密码*/
function upDatePwdUser(node,type){
    var id=$(node).attr("data-id");
    mccmsa.ajax({
        url:"devicePwdInfo/upDatePwds",
        method:"post",
        data:{id:id,type:type,pwdType:3},
        success:function(data){
            if(200==data.status){
                var parent=$(node).parent();
                $(node).remove();
                if(1==type){
                    layer.msg("启用指令已发送");
                    mccmsa.hashChange();
                    //parent.append('<span class="btn btn-primary radius" data-id="'+id+'" onclick="upDatePwdUser(this,0)">冻结</span>');
                }else if(2==type){
                    layer.msg("冻结已发送");
                    mccmsa.hashChange();
                    //parent.append('<span class="btn btn-warning-outline radius" data-id="'+id+'" onclick="upDatePwdUser(this,1)">启用</span>');
                }
            }
        }
    })
}
function deluPwds(node){
    if(!confirm("确定删除吗?")){
        return;
    }
    var id=$(node).attr("data-id");
    mccmsa.ajax({
        url:"devicePwdInfo/deluPwds",
        method:"post",
        data:{id:id},
        success:function(data){
            if(200==data.success){
                layer.msg("删除指令已发送");
                mccmsa.hashChange();
            }else{
                layer.msg("删除指令已发送");
                mccmsa.hashChange();
            }
        }
    })

}
function showPwds(){       //显示临时密码弹窗
    $('#pwdDialog').modal('show');
    $("#pwdDialog_address").html($("#door_title").html()+" 室外大门锁");
    $.ajax({
        url:"devicePwdInfo/getNewPwd",
        method:"post",
        data:{id: $.bbq.getState("id")},
        dataType:"json",
        success:function(data){
            $("#pwdDialog_pwd").html(data.result);
        }
    });
}
function subPwdDialog(){                  //提交生成临时密码
    var json=$("#pwdDialog_form").serializeJson();
    json.centerControlId= $.bbq.getState("id");
    json.password=$("#pwdDialog_pwd").html();
    if(json.type==1){
        if(json.beginTimeStr==""&&json.endTimeStr==""){
            return;
        }
    }
    mccmsa.ajax({
        url:"devicePwdInfo /addCenterPwd",
        method:"post",
        data:json,
        success:function(data){
            if(200==data.status){
                layer.msg("生成密码指令已发送");
            }else{
                layer.msg(data.message);
            }
        }
    });
    $('#pwdDialog').modal('hide');
}
/*function pwd2Mobile(){
    var mobile=$("#pwd_mobilePhone").val();
    if(!mobile||mobile==""){
        return;
    }
    mccmsa.ajax({
        url:""
    })
}*/
function gotoPwdsRecord(){
   var id=$.bbq.getState("id");
    mccmsa.goTo("pwds_record","door_lock",{id:id});
}


$("#searchbtn").click(function(e){
	$(".searchbox").toggleClass("active");
});
$("#weixin_btn").mouseover(function(){
	$("#weixin_code").addClass("active")
});
$("#weixin_btn").mouseout(function(){
	$("#weixin_code").removeClass("active")
});
$(function(){
	clock(new Date(),$("#myClock"));
	mccmsa.hashChange();
});
$(function(){
	//zTree树节点点击时显示编辑，删除
	$("#mainContainer").on("click","#permissionManage .treeTip a",function(event){
		$(".treeFunction").remove();
		var html = "<div class='treeFunction'><span class='treeEdit' onClick='getEditPermissionData(this)'>编辑</span><span class='treeDel' data-toggle='modal' href='#myModal' onclick='modalUser(this)'>删除</span></div>";
		$(this).append(html)
	});
	//权限，当权限类型选为功能时，隐藏父级权限选择
	$("#mainContainer").on("change","#onClickDataTable #select",function(event){
		if($(this).val()==2){
			$("#permFirstTr").hide();
		}else{
			$("#permFirstTr").show();
		}
	});

});
(function($){
	$.fn.serializeJson=function(){
		var serializeObj={};
		var array=this.serializeArray();
		var str=this.serialize();
		$(array).each(function(){
			if(serializeObj[this.name]){
				if($.isArray(serializeObj[this.name])){
					serializeObj[this.name].push(this.value);
				}else{
					serializeObj[this.name]=[serializeObj[this.name],this.value];
				}
			}else{
				serializeObj[this.name]=this.value;
			}
		});
		return serializeObj;
	};
})(jQuery);
function clock(date,node){
	node.html(date.format("yyyy-MM-dd hh:mm:ss"));
	window.setInterval(function(){
		date=new Date(date.getTime()+1000);
		node.html(date.format("yyyy-MM-dd hh:mm:ss"));
	},1000)
}
Date.prototype.format = function(format){
	var o = {
		"M+" : this.getMonth()+1, //month
		"d+" : this.getDate(), //day
		"h+" : this.getHours(), //hour
		"m+" : this.getMinutes(), //minute
		"s+" : this.getSeconds(), //second
		"q+" : Math.floor((this.getMonth()+3)/3), //quarter
		"S" : this.getMilliseconds() //millisecond
	}

	if(/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
	}

	for(var k in o) {
		if(new RegExp("("+ k +")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
		}
	}
	return format;
};
function initCity(){
	$("#province").on("change",function(){
		var str="<option value='' selected='selected'>市区</option>";
		$("#area").html("<option value='' selected='selected'>行政区域</option>");
		$("#city").html(str);
		if($(this).val()!=''){
			$.ajax({
				url:'area/getCitiesByCondition',
				type:'get',
				dataType: 'json',
				data:{
					"provinceId":$(this).val()
				},
				success: function(json) {
					for(var i=0;i<json.result.length;i++){
						str+="<option value='"+json.result[i].cityID+"'>"+json.result[i].city+"</option>";
					}
					$("#city").html(str);
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("网络出现异常");
				}
			});
		}
	});
	$("#city").on("change",function(){
		var str="<option value='' selected='selected'>行政区域</option>";
		$("#area").html(str);
		if($(this).val()!=''){
			$.ajax({
				url:'area/getAreasByCondition',
				type:'get',
				dataType: 'json',
				data:{
					"cityId":$(this).val()
				},
				success: function(json) {
					for(var i=0;i<json.result.length;i++){
						str+="<option value='"+json.result[i].areaID+"'>"+json.result[i].area+"</option>";
					}
					$("#area").html(str);
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("网络出现异常");
				}
			});
		}
	});
}
var province=[{"id":1,"province":"北京","provinceid":110000},{"id":2,"province":"天津","provinceid":120000},{"id":3,"province":"河北","provinceid":130000},{"id":4,"province":"山西","provinceid":140000},{"id":5,"province":"内蒙古","provinceid":150000},{"id":6,"province":"辽宁","provinceid":210000},{"id":7,"province":"吉林","provinceid":220000},{"id":8,"province":"黑龙江","provinceid":230000},{"id":9,"province":"上海","provinceid":310000},{"id":10,"province":"江苏","provinceid":320000},{"id":11,"province":"浙江","provinceid":330000},{"id":12,"province":"安徽","provinceid":340000},{"id":13,"province":"福建","provinceid":350000},{"id":14,"province":"江西","provinceid":360000},{"id":15,"province":"山东","provinceid":370000},{"id":16,"province":"河南","provinceid":410000},{"id":17,"province":"湖北","provinceid":420000},{"id":18,"province":"湖南","provinceid":430000},{"id":19,"province":"广东","provinceid":440000},{"id":20,"province":"广西","provinceid":450000},{"id":21,"province":"海南","provinceid":460000},{"id":22,"province":"重庆","provinceid":500000},{"id":23,"province":"四川","provinceid":510000},{"id":24,"province":"贵州","provinceid":520000},{"id":25,"province":"云南","provinceid":530000},{"id":26,"province":"西藏","provinceid":540000},{"id":27,"province":"陕西","provinceid":610000},{"id":28,"province":"甘肃","provinceid":620000},{"id":29,"province":"青海","provinceid":630000},{"id":30,"province":"宁夏","provinceid":640000},{"id":31,"province":"新疆","provinceid":650000},{"id":32,"province":"台湾","provinceid":710000},{"id":33,"province":"香港","provinceid":810000},{"id":34,"province":"澳门","provinceid":820000}];

$(function(){
	//zTree树节点点击时显示编辑，删除
	$("#mainContainer").on("click","#permissionManage .treeTip a",function(event){
		$(".treeFunction").remove();
		var html = "<div class='treeFunction'><span class='treeEdit' onClick='getEditPermissionData(this)'>编辑</span><span class='treeDel' data-toggle='modal' href='#myModal' onclick='modalUser(this)'>删除</span></div>";
		$(this).append(html)
	});
//权限，当权限类型选为功能时，隐藏父级权限选择
	$("#mainContainer").on("change","#onClickDataTable #select",function(event){
		if($(this).val()==2){
			$("#permFirstTr").hide();
		}else{
			$("#permFirstTr").show();
		}
	});
	$(".logout").on("click",function(){
		window.location="logout";
	})
});


/**
 * Created by Jay on 2016/5/17.
 */
function message_management(){
    //头部按钮
    var msg_status= $.bbq.getState("status")||3;
    $("#user_form").on("click","input",function() {
        var type = $(this).attr("search_type");
        console.log($(this).attr("search_type"));
        mccmsa.ajax({
            url: "messageInfo/getMessageInfoByCondition",
            data: {pageNo: 1, pageSize: 20, status:msg_status, type: type},
            method: "POST",
            success: function (data){
                console.log(data);
                mccmsa.getHtmlFromLocalTemplate({
                    templateId: "getColumnTableData",
                    container: $("#ColumnTableData"),
                    data: data
                });
                //生成分页
                $("#layPage").createPage({
                    pageCount: data.result.pageCount,
                    current: data.result.pageNo,
                    backFn:function(p){
                        mccmsa.ajax({
                            url:"messageInfo/getMessageInfoByCondition",
                            data:{pageNo:p,pageSize:20,status:msg_status},
                            method:"POST",
                            success:function(data){
                                mccmsa.getHtmlFromLocalTemplate({
                                    templateId:"getColumnTableData",
                                    container: $("#ColumnTableData"),
                                    data:data
                                });
                            }
                        })
                    }
                });
            }
        })
    });
    mccmsa.checkAll();//checkbox
    //底部按钮
    mccmsa.ajax({
        url:"messageInfo/getMessageInfoByCondition",
        data:{pageNo:1,pageSize:20,status:msg_status},
        method:"POST",
        success: function (data) {
            console.log(data);
            mccmsa.getHtmlFromLocalTemplate({
                templateId:"getColumnTableData",
                container: $("#ColumnTableData"),
                data:data
            });
            //生成分页
            $("#layPage").createPage({
                pageCount: data.result.pageCount,
                current: data.result.pageNo,
                backFn:function(p){
                    mccmsa.ajax({
                        url:"messageInfo/getMessageInfoByCondition",
                        data:{pageNo:p,pageSize:20,status:msg_status},
                        method:"POST",
                        success:function(data){
                            mccmsa.getHtmlFromLocalTemplate({
                                templateId:"getColumnTableData",
                                container: $("#ColumnTableData"),
                                data:data
                            });
                        }
                    })
                }
            });
            //删除
            $(".m_c_delete").on("click",function(){
                //console.log($('.checklist input:checked').length);
                var ids = '';
                var check_ids=false;//如果没有ids就false
                var sub = false;
                for(i = 0; i<$('.checklist input:checked').length; i++) {
                    if ($('.checklist input:checked').eq(i).val()) {
                        ids += $('.checklist input:checked').eq(i).val() + ',';
                    }
                }
                if(ids)check_ids = true;
                mccmsa.operation({
                    flag:　true,
                    name: '删除',
                    url: "messageInfo/getMessageInfoByCondition",
                    data:{pageNo:1,pageSize:20,status:msg_status,id:ids},
                    check_ids:check_ids,
                    method: "POST",
                })
                //生成分页
                $("#layPage").createPage({
                    pageCount: data.result.pageCount,
                    current: data.result.pageNo,
                    backFn:function(p){
                        mccmsa.ajax({
                            url:"messageInfo/getMessageInfoByCondition",
                            data:{pageNo:p,pageSize:20,status:msg_status},
                            method:"POST",
                            success:function(data){
                                mccmsa.getHtmlFromLocalTemplate({
                                    templateId:"getColumnTableData",
                                    container: $("#ColumnTableData"),
                                    data:data
                                });
                            }
                        })
                    }
                });
            })
            //已读
            $(".mack_read").on("click",function(){
                var ids = '';
                var check_ids=false;//如果没有ids就false
                var sub = false;
                for(i = 0; i<$('.checklist input:checked').length; i++) {
                    if ($('.checklist input:checked').eq(i).val()) {
                        ids += $('.checklist input:checked').eq(i).val() + ',';
                    }
                }
                if(ids)check_ids = true;
                mccmsa.operation({
                    flag:　true,
                    name: '标记',
                    url: "messageInfo/getMessageInfoByCondition",
                    data:{pageNo:1,pageSize:20,status:msg_status,id:ids},
                    check_ids:check_ids,
                    method: "POST"
                })
                //生成分页
                $("#layPage").createPage({
                    pageCount: data.result.pageCount,
                    current: data.result.pageNo,
                    backFn:function(p){
                        mccmsa.ajax({
                            url:"messageInfo/getMessageInfoByCondition",
                            data:{pageNo:p,pageSize:20,status:msg_status},
                            method:"POST",
                            success:function(data){
                                mccmsa.getHtmlFromLocalTemplate({
                                    templateId:"getColumnTableData",
                                    container: $("#ColumnTableData"),
                                    data:data
                                });
                            }
                        })
                    }
                });
            } )
            //消息详情
            $("#userManage").on("click",".hover_change",function(){
                var mess_id=$(this).prev().children("input").attr("value");
                mccmsa.goTo("message_management_detail","message_management",{id:mess_id});
            })

        }

    });
    //ColumnTableData
}
/**
 * Created by Jay on 2016/5/19.
 */
function message_management_detail(){
    var id=$.bbq.getState("id")||1;
    console.log("id=",id);
        mccmsa.ajax({
        //url: "messageMember/getMessageMember/"+id,
        url:"messageMember/getMessageMember/"+id,
        method:"get",
        success:function (data) {
          $(".mess_title").html(data.messageInfo.title);
          $(".mess_time").html(data.result.messageInfo.createTime);
          $(".mess_content").html(data.result.messageInfo.content);
        }
    });
}
//客户基本资料
var usermange_username="";
var usermange_id="";
function myZl(){
    var id=sessionStorage.getItem("id");
    mccmsa.ajax({
        url: "user/getUser/"+id,
        method: "get",
        dataType:"json",
        success: function (data) {
            usermange_username=data.result.username;
            usermange_id=data.result.id;
            $.ajax({
                url:"contractInfo/getUserContractInfos",
                data:{"username":data.result.username},
                method: "post",
                dataType:"json",
                success:function(msg){
                    data.ht=msg.result;
                    mccmsa.getHtmlFromLocalTemplate({
                        templateId: "user_manage_detail",
                        container: $("#mainContainer"),
                        data: data
                    });
                }
            });
        }
    });
}


/*活动*/
//活动列表
function playListClick(){
	$("#Huifold a[href=playList]").click();
}
function playList(pageNo){
	 //给栏目表录入数据
	if(!pageNo){pageNo=1}		//分页页数
    mccmsa.ajax({
        url:"activity/list/0?pageNo="+pageNo+"&pageSize=8",
        method:"Get",
        success:function(json){
        	for(var i in json.result.resultList){
        		json.result.resultList[i].beginTime=returnDate(json.result.resultList[i].beginTime);
        		json.result.resultList[i].status=returnStatus(json.result.resultList[i].status);
        	}

        	Handlebars.registerHelper("addOne",function(index,options){
				   return parseInt(index)+1+(json.result.pageNo-1)*json.result.pageSize;
			});
            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navMain",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getColumnTableData",
                container: $("#ColumnTableData"),
                data:json
            });
			pageHtml(json);		//生成分页
            $("#playList").show();
            $("#onClickDataTable").hide(); 
			
            var scrollbarWidth = $('.table-maxHeight')[0].offsetWidth - $('.table-maxHeight')[0].scrollWidth;
            $("table:eq(0)").css("paddingRight",scrollbarWidth);    //获取滚动条宽度并赋值到表头padding-right，对齐
        }
    })
}
//活动查询
function playListCheck(obj){
	mccmsa.ajax({
        url:"activity/getById/"+$(obj).parents("tr").attr("actId"),
        method:"GET",
        success:function(json){
        	json.result.beginTime=returnDate(json.result.beginTime);
        	json.result.endTime=returnDate(json.result.endTime);
        	json.result.enrollBeginTime=returnDate(json.result.enrollBeginTime);
        	json.result.enrollEndTime=returnDate(json.result.enrollEndTime);
        	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navCheck",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getCheckData",
                container: $("#onClickDataTable"),
                data:json
            });
            
            if(json.result.actPhotoName!=null){
            	$("#preview").attr("src","upload/enterprice/image/"+json.result.actPhotoName);
				$("#preview").parent().find(".shadeFile").html(json.result.actPhotoName.substring(json.result.actPhotoName.lastIndexOf("/")+1))
			}
            
            
            $("#playList").hide();
            $("#onClickDataTable").show(); 
            
            /*//获取滚动条宽度并赋值到表头padding-right，对齐
        	//实例化编辑器
        	//建议使用工厂方法getEditor创建和引用编辑器实例，如果在某个闭包下引用该编辑器，直接调用UE.getEditor('editor')就能拿到相关的实例
            editor = new UE.ui.Editor();
            editor.render("editor");*/
        }
    })
}
//活动编辑
function playListEdit(obj){
	mccmsa.ajax({
        url:"activity/getById/"+$(obj).parents("tr").attr("actId"),
        method:"GET",
        success:function(json){
        	json.result.beginTime=returnDate(json.result.beginTime);
        	json.result.endTime=returnDate(json.result.endTime);
        	json.result.enrollBeginTime=returnDate(json.result.enrollBeginTime);
        	json.result.enrollEndTime=returnDate(json.result.enrollEndTime);
        	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navCheck",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getEditData",
                container: $("#onClickDataTable"),
                data:json
            });
            
            if(json.result.actPhotoName!=null){
            	$("#preview").attr("src","upload/enterprice/image/"+json.result.actPhotoName);
				$("#preview").parent().find(".shadeFile").html(json.result.actPhotoName.substring(json.result.actPhotoName.lastIndexOf("/")+1))
			}
            
            $("#playList").hide();
            $("#onClickDataTable").show(); 
            
            dataLay();
            
            //获取滚动条宽度并赋值到表头padding-right，对齐
        	//实例化编辑器
        	//建议使用工厂方法getEditor创建和引用编辑器实例，如果在某个闭包下引用该编辑器，直接调用UE.getEditor('editor')就能拿到相关的实例
            editor = new UE.ui.Editor();
            editor.render("editor");
            
            //判断ueditor 编辑器是否创建成功
			editor.addListener("ready", function() {
				// editor准备好之后才可以使用
				if(json.result.moreDetails!=null){
					editor.setContent(json.result.moreDetails);
				}
			});
            
            $("#onClickDataTable>tbody>tr:last").after('<tr><td class="col-1 table-bgc-f5"></td><td class="text-l col-11"> <input class="btn btn-primary radius"  onClick="playListEditPost()" type="submit" value="提交"></td></tr>');
        }
    })
}
function dataLay(){
	laydate({
        elem: '#beginTime',
		istime: true,
		format: 'YYYY-MM-DD hh:mm:ss', // 分隔符可以任意定义，该例子表示只显示年月
    });
	laydate({
        elem: '#endTime',
		istime: true,
		format: 'YYYY-MM-DD hh:mm:ss', // 分隔符可以任意定义，该例子表示只显示年月
    });
	laydate({
        elem: '#enrollBeginTime',
		istime: true,
		format: 'YYYY-MM-DD hh:mm:ss', // 分隔符可以任意定义，该例子表示只显示年月
    });
	laydate({
        elem: '#enrollEndTime',
		istime: true,
		format: 'YYYY-MM-DD hh:mm:ss', // 分隔符可以任意定义，该例子表示只显示年月
    });
}
function playListEditPost(){
	mccmsa.ajax({
        url:"activity/editAct",
        method:"POST",
		data:{
			"actId":$("#onClickDataTable tr:eq(0)").attr("actid"),
			"actTopic":$("#actTopic").val(),
			"actPhotoName":$("#preview").attr("src").substring($("#preview").attr("src").lastIndexOf("/")+1),
			"priKey":$("#priKey").val(),
			"enrollPrice":$("#enrollPrice").val(),
			"enrollLimit":$("#enrollLimit").val(),
			"moreDetails":editor.getContent(),
			"address":$("#address").val(),
			"detailAdd":$("#detailAdd").val(),
			"beginTime":$("#beginTime").val(),
			"endTime":$("#endTime").val(),
			"enrollBeginTime":$("#enrollBeginTime").val(),
			"enrollEndTime":$("#enrollEndTime").val(),
			"status":$(".select option:selected").val()
		},
        success:function(json){
        	alert(json.message);
        	playList();
        }
    })
}


//新增数据

function playListNew(){
	mccmsa.ajax({
        url:"activity/getById/1",
        method:"GET",
        success:function(json){
        	
        	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navNewData",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getNewData",
                container: $("#onClickDataTable")
            });
            
            $("#playList").hide();
            $("#onClickDataTable").show(); 
            
            dataLay();
            
            //获取滚动条宽度并赋值到表头padding-right，对齐
        	//实例化编辑器
        	//建议使用工厂方法getEditor创建和引用编辑器实例，如果在某个闭包下引用该编辑器，直接调用UE.getEditor('editor')就能拿到相关的实例
            editor = new UE.ui.Editor();
            editor.render("editor");
            
            $("#onClickDataTable>tbody>tr:last").after('<tr><td class="col-1 table-bgc-f5"></td><td class="text-l col-11"> <input class="btn btn-primary radius"  onClick="playListPostNew()" type="submit" value="提交"></td></tr>');
        }
    })  
}
function playListPostNew(){
	mccmsa.ajax({
        url:"activity/addAct",
        method:"POST",
        data:{
			"actId":$("#onClickDataTable tr:eq(0)").attr("actid"),
			"actTopic":$("#actTopic").val(),
			"actPhotoName":$("#preview").attr("src").substring($("#preview").attr("src").lastIndexOf("/")+1),
			"priKey":$("#priKey").val(),
			"enrollPrice":$("#enrollPrice").val(),
			"enrollLimit":$("#enrollLimit").val(),
			"moreDetails":editor.getContent(),
			"address":$("#address").val(),
			"detailAdd":$("#detailAdd").val(),
			"beginTime":$("#beginTime").val(),
			"endTime":$("#endTime").val(),
			"enrollBeginTime":$("#enrollBeginTime").val(),
			"enrollEndTime":$("#enrollEndTime").val(),
			"status":$(".select option:selected").val()
		},
        success:function(json){
        	alert(json.message);
        	playList();
        }
    })
}

//删除
function playListDel(obj){
	$("#myModal").attr("actid",$(obj).parents("tr").attr("actId"));
}
function playListDelSure(obj){
	mccmsa.ajax({
        url:"activity/delAct/"+$("#myModal").attr("actid"),
        method:"POST",
        success:function(json){
        	alert(json.message);
        	$(".close").click();
        	playList();
        }
    })
}



/*活动end*/

/*参与人*/
function participant(obj){
	var actid = $(obj).parents("tr").attr("actid");
	mccmsa.getHtmlFromRemoteTemplate({
        templateName:"participant.hbs",
        container: $("#mainContainer")
    });
	new participantList(1,actid);
}
function participantList(pageNo,actid){
	if(!actid){
		actid=$("#participantList").attr("actid")
	}
	if(!pageNo){
		pageNo=1
	}
	mccmsa.ajax({
        url:"back/activity/attendee/getByAct/"+actid+"?pageSize=8&pageNo="+pageNo,
        method:"GET",
        success:function(json){
        	for(var i in json.result.resultList){
				json.result.resultList[i].enrollTime=returnDate(json.result.resultList[i].enrollTime);
				json.result.resultList[i].status=returnStatus(json.result.resultList[i].status);
			}
        	
        	Handlebars.registerHelper("addOne",function(index,options){
				   return parseInt(index)+1+(json.result.pageNo-1)*json.result.pageSize;
			});
        	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
        		templateId: "navMain",
        		container: $("#pathContainer")
        	});

        	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
        		templateId: "getColumnTableData",
        		container: $("#ColumnTableData"),
        		data:json
        	});
        	if(actid){
        		$("#participantList").attr("actid",actid);
        	}
        	if(json.result.resultList[0]!=null){
        		$("#pathContainer input").attr("activityId",json.result.resultList[0].activityId);
        	}
        	$("#participantList").show();
        	$("#htmlCheckContent,#onClickDataTable").hide();
        	pageHtml(json);		//生成分页
        }
    })
}
//编辑
function participantEdit(obj){
	mccmsa.ajax({
        url:"back/activity/attendee/getById/"+$(obj).parents("tr").attr("actAttId"),
        method:"GET",
        success:function(json){
        	json.result.enrollTime=returnDate(json.result.enrollTime);
        	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navEdit",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getEditData",
                container: $("#onClickDataTable"),
                data:json
            });
            if(json.result.attSex=="男"){
            	$("#select option:eq(0)").attr("selected","selected");
            }else if(json.result.attSex=="女"){
            	$("#select option:eq(1)").attr("selected","selected");
            }

            laydate({
                elem: '#bornDate',
        		format: 'YYYY-MM-DD', // 分隔符可以任意定义，该例子表示只显示年月
            });
            
            $("#participantList").hide();
            $("#onClickDataTable").show(); 
        }
    })
}
function participantEditPost(){
	mccmsa.ajax({
        url:"back/activity/attendee/editAtt",
        method:"POST",
        data:{
        	"actAttId":$("#onClickDataTable>tbody>tr:eq(0)").attr("actAttId"),
        	"attName":$("#attName").val(),
        	"attSex":$("#select").val(),
        	"attPhone":$("#attPhone").val(),
        	"attIdNum":$("#attIdNum").val(),
        	"bornDate":$("#bornDate").val(),
        	"attComment":$("#attComment").val(),
        	"status":"1"
        },
        success:function(json){
        	alert(json.message);
        	participantList();
        }
    })
}
//新增
function participantNew(obj){
	var activityid = $(obj).attr("activityid");
	mccmsa.ajax({
        url:"back/activity/attendee/getById/1",
        method:"GET",
        success:function(json){
        	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navNewData",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getNewData",
                container: $("#onClickDataTable")
            });

            
            laydate({
                elem: '#bornDateNew',
        		format: 'YYYY-MM-DD', // 分隔符可以任意定义，该例子表示只显示年月
            });
            
            $("#participantNewPost").attr("activityid",activityid);
            $("#participantList").hide();
            $("#onClickDataTable").show();
        }
    })
    	
}

function participantNewPost(obj){
	mccmsa.ajax({
        url:"back/activity/attendee/addAtt",
        method:"POST",
        data:{
        	"activityId":$("#participantList").attr("actid"),
        	"attName":$("#attName").val(),
        	"attSex":$("#select").val(),
        	"attPhone":$("#attPhone").val(),
        	"attIdNum":$("#attIdNum").val(),
        	"bornDate":$("#bornDateNew").val(),
        	"attComment":$("#attComment").val(),
        	"status":"1"
        },
        success:function(json){
        	alert(json.message);
        	participantList();
        }
    })
}

//删除
function participantDel(obj){
	$("#myModal").attr("actattid",$(obj).parents("tr").attr("actattid"));
}
function participantDelPost(){
	mccmsa.ajax({
        url:"back/activity/attendee/delAtt/"+$("#myModal").attr("actattid"),
        method:"DELETE",
        success:function(json){
        	alert(json.message);
        	participantList();
        	$(".close").click();
        }
    })
}
/*参与人end*/


/*会员列表*/
function memberList(pageNo){
	 //给栏目表录入数据
	if(!pageNo){pageNo=1}		//分页页数
    mccmsa.ajax({
        url:"member/getMemberAll?pageNo="+pageNo+"&pageSize=8",
        method:"Get",
        success:function(json){
        	for(var i in json.result.resultList){
        		json.result.resultList[i].regisTime=returnDate(json.result.resultList[i].regisTime);
        		json.result.resultList[i].status=returnStatusMember(json.result.resultList[i].status);
        	}
        	Handlebars.registerHelper("addOne",function(index,options){
				   return parseInt(index)+1+(json.result.pageNo-1)*json.result.pageSize;
			});
            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navMain",
                container: $("#pathContainer")
            });
            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getColumnTableData",
                container: $("#ColumnTableData"),
                data:json
            });
			pageHtml(json);		//生成分页
            $("#memberList").show();
            $("#onClickDataTable,.memberNav").hide(); 
            
            var scrollbarWidth = $('.table-maxHeight')[0].offsetWidth - $('.table-maxHeight')[0].scrollWidth;
            $("table:eq(0)").css("paddingRight",scrollbarWidth);    //获取滚动条宽度并赋值到表头padding-right，对齐
            $(".layPage").hide();
        }
    })
}
//密码
function setPasswordMember(obj){//修改密码内容框
		var id = $(obj).parents("tr").attr("comid");
		var mobile = $(obj).attr("mobile");
		mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
			templateId: "navPassword",
			container: $("#pathContainer")
		});
		mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
			templateId: "getSetPassword",
			container: $("#onClickDataTable"),
		});
		$("#onClickDataTable tr:first").attr({
			"memberid":id,
			"mobile":mobile
		});
		$("#onClickDataTable").show();
        $("#memberList,.memberNav").hide();
        $("#memberPost").attr("userName",$(obj).attr("userName"));
}
function postPasswordMember(obj){//提交修改密码内容框
	mccmsa.ajax({
		url:"member/updateAccountSafe", //需要添加参数，看接口需要
		method:"POST",
		data:{
			"id":$("#onClickDataTable tr:first").attr("memberid"),
			"mobile":$("#onClickDataTable tr:first").attr("mobile"),
			"username":$("#memberPost").attr("userName"),
			"userPassword":$("#userPassword").val(),
			"newPassword":$("#newPassword").val()
		},
		success:function(json){
			alert(json.message);
			$("#pathContainer input").click();
		}
	})
}
//查看
function memberCheck(obj,id){
	if(obj!=""){
		id=$(obj).parents("tr").attr("comId");
	}
	mccmsa.ajax({
        url:"member/getMemberInfo/"+id,
        method:"GET",
        success:function(json){
        	json.result.birthday=returnDateDay(json.result.birthday);
        	
        	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navCheck",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getCheckData",
                container: $("#onClickDataTable"),
                data:json
            });
            $("#onClickDataTable,.memberNav").show();
            $("#memberList").hide();
            
            $("#preview").attr("src","upload/enterprice/image/"+json.result.userHead);
            $(".memberNav").attr("comId",$(obj).parents("tr").attr("comId"));
            if(!json.result.identity[0]){json.result.identity[0]=""}
            if(!json.result.memberLevel){json.result.memberLevel=""}
            getDrVip(json.result.identity[0].id,json.result.memberLevel.id);
            isMemberCheck();//判断是否查看，否则table的border为0
            $("#status option[value='"+json.result.status+"']").attr("selected","selected");
            $("#isBlock option[value='"+json.result.isBlock+"']").attr("selected","selected");
            $("#regisFrom option[value='"+json.result.regisFrom+"']").attr("selected","selected");
            $(".layPage").hide();
        }
    })
}
$(function(){
	$("#mainContainer").on("click",".memberNav ul li",function(){
		var val = $(this).index();
		var id = $(".memberNav").attr("comId");
		$(".tip").removeClass("tip");
		$(this).addClass("tip");
		switch(val){
			case 0:
				return memberCheck("",id);
			case 1:
				$(".layPage").attr("fun","memberDynamicList");
				return memberDynamicList("",id);
			case 2:
				return memberBasisData(id);
			case 3:
				$(".layPage").attr("fun","memberlinkmanData")
				return memberlinkmanData("",id);
			case 4:
				$(".layPage").attr("fun","memberCheckupReporting")
				return memberCheckupReporting("",id);
		}
	})
})


function memberDynamicList(pageNo,id){
	if(!pageNo){pageNo=1}
	if(!id){id=$(".memberNav").attr("comId")}
	mccmsa.ajax({
        url:"users/getDynamicByAccountId/"+id+"?pageNo="+pageNo+"&pageSize=8",
        method:"GET",
        success:function(json){
        	Handlebars.registerHelper("addOne",function(index,options){
				   return parseInt(index)+1+(json.result.pageNo-1)*json.result.pageSize;
			});
        	for(var i in json.result.resultList){
        		json.result.resultList[i].checkTime=returnDate(json.result.resultList[i].checkTime);
        	}
            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getCheckDynamicData",
                container: $("#onClickDataTable"),
                data:json
            });
            pageHtml(json,$(".layPage"))
    		$(".layPage").show();
        }
    })
}
function memberDynamicEdit(obj){
	var id = $(obj).parents("tr").attr("comid");
	mccmsa.ajax({
        url:"users/getDynamicDataById/"+id,
        method:"GET",
        success:function(json){
        	json.result.checkTime=returnDateDay(json.result.checkTime);
        	json.result.sleep.hypnagogicTime=returnDate(json.result.sleep.hypnagogicTime);
        	
            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getCheckDynamicEdit",
                container: $("#onClickDataTable"),
                data:json
            });
            laydate({
                elem: '#checkTime',
        		format: 'YYYY-MM-DD', // 分隔符可以任意定义，该例子表示只显示年月
            });
        	laydate({
                elem: '#hypnagogicTime',
                istime: true,
        		format: 'YYYY-MM-DD hh:mm:ss', // 分隔符可以任意定义，该例子表示只显示年月
            });
        	
        	$("#isSleep option[value='"+json.result.sleep.sleepQuality+"']").attr("selected","selected");
        	$("#isSiesta option[value='"+json.result.sleep.afternoonNap+"']").attr("selected","selected");
        	$("#defecate option[value='"+json.result.defecate+"']").attr("selected","selected");
        	$("#apptite option[value='"+json.result.apptite+"']").attr("selected","selected");
        	$("#threeMeals option[value='"+json.result.threeMeals+"']").attr("selected","selected");
        	$("#smoothBowel option[value='"+json.result.smoothBowel+"']").attr("selected","selected");
        	
        	for(var i in json.result.emotion){
        		$("#is-emotion label").each(function(){
        			if($(this).text()==json.result.emotion[i].name){
        				$(this).prev().prop("checked",true);
        			}
        		});
        	}
        	for(var i in json.result.sports){
        		$("#is-sport label").each(function(){
        			if($(this).text()==json.result.sports[i].name){
        				$(this).prev().prop("checked",true);
        			}
        		});
        	}
        	
        	$("#memberDynamicNewPost").attr("comId",id);
            $(".layPage").hide();
        }
    })
}
function memberDynamicEditPost(obj){
	var sport = "[";
	var emotions = "["
	$("#is-emotion input").each(function(){
		if($(this).prop("checked")){
			emotions+= "{'name':'"+$(this).next().text()+"'},";
		}
	})
	$("#is-sport input").each(function(){
		if($(this).prop("checked")){
			sport+= "{'name':'"+$(this).next().text()+"'},";
		}
	})
	emotions = emotions.substring(0,emotions.length-1)+"]";
	sport = sport.substring(0,sport.length-1)+"]";
	mccmsa.ajax({
        url:"users/editDynamicData",
        method:"POST",
        data:{
        	"id":$("#memberDynamicNewPost").attr("comId"),
        	"defecate":$("#defecate").val(),
        	"temperature":$("#temperature").val(),
        	"systolicPressure":$("#systolicPressure").val(),
        	"diastolicPressure":$("#diastolicPressure").val(),
        	"bloodGlucose":$("#bloodGlucose").val(),
        	"heartRate":$("#heartRate").val(),
        	"checkTime":$("#checkTime").val(),
        	"sport":(sport.length-1)?sport:undefined,
        	"emotions":(emotions.length-1)?emotions:undefined,
        	"apptite":$("#apptite").val(),
        	"threeMeals":$("#threeMeals").val(),
        	"waterIntake":$("#waterIntake").val(),
        	"runDuration":$("#runDuration").val(),
        	"smoothBowel":$("#smoothBowel").val(),
        	"micturitionUnmber":$("#micturitionUnmber").val(),
        	"sleep.hypnagogicTime":$("#hypnagogicTime").val(),
        	"sleep.sleepTime":$("#sleepTime").val(),
        	"sleep.sleepQuality":$("#isSleep").val(),
        	"sleep.afternoonNap":$("#isSiesta").val()
        },
        success:function(json){
        		alert(json.message);
        		memberDynamicList();
        }
    })
}



function memberDynamicNew(){
    mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
        templateId: "getCheckDynamicNew",
        container: $("#onClickDataTable")
    });
    setTimeout(function(){
    	laydate({
            elem: '#checkTime',
    		format: 'YYYY-MM-DD', // 分隔符可以任意定义，该例子表示只显示年月
        });
    	laydate({
            elem: '#hypnagogicTime',
            istime: true,
    		format: 'YYYY-MM-DD hh:mm:ss', // 分隔符可以任意定义，该例子表示只显示年月
        });
    },100)
    $(".layPage").hide();
}
function memberDynamicNewPost(){
	var sport = "[";
	var emotions = "["
	$("#is-emotion input").each(function(){
		if($(this).prop("checked")){
			emotions+= "{'name':'"+$(this).next().text()+"'},";
		}
	})
	$("#is-sport input").each(function(){
		if($(this).prop("checked")){
			sport+= "{'name':'"+$(this).next().text()+"'},";
		}
	})
	emotions = emotions.substring(0,emotions.length-1)+"]";
	sport = sport.substring(0,sport.length-1)+"]";
	mccmsa.ajax({
        url:"users/addDynamic",
        method:"POST",
        data:{
        	"accountId":$(".memberNav").attr("comId"),
        	"defecate":$("#defecate").val(),
        	"temperature":$("#temperature").val(),
        	"systolicPressure":$("#systolicPressure").val(),
        	"diastolicPressure":$("#diastolicPressure").val(),
        	"bloodGlucose":$("#bloodGlucose").val(),
        	"heartRate":$("#heartRate").val(),
        	"checkTime":$("#checkTime").val(),
        	"sport":(sport.length-1)?sport:undefined,
        	"emotions":(emotions.length-1)?emotions:undefined,
        	"apptite":$("#apptite").val(),
        	"threeMeals":$("#threeMeals").val(),
        	"waterIntake":$("#waterIntake").val(),
        	"runDuration":$("#runDuration").val(),
        	"smoothBowel":$("#smoothBowel").val(),
        	"micturitionUnmber":$("#micturitionUnmber").val(),
        	"sleep.hypnagogicTime":$("#hypnagogicTime").val(),
        	"sleep.sleepTime":$("#sleepTime").val(),
        	"sleep.sleepQuality":$("#isSleep").val(),
        	"sleep.afternoonNap":$("#isSiesta").val()
        },
        success:function(json){
        	alert(json.message);
        	memberDynamicList();
        }
    })
}





function memberBasisData(id){
	mccmsa.ajax({
        url:"users/getDataByAccountId/"+id,
        method:"GET",
        success:function(json){
            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getCheckBasisData",
                container: $("#onClickDataTable"),
                data:json
            });
            $(".layPage").hide();
        }
    })
}

function memberlinkmanData(pageNo,id){
	//给栏目表录入数据
	if(!pageNo){pageNo=1}		//分页页数
	if(!id){id=$("#onClickDataTable").attr("comid")}
	mccmsa.ajax({
        url:"users/getContactByAccountId/"+id+"?pageNo="+pageNo+"&pageSize=8",
        method:"GET",
        success:function(json){
        	Handlebars.registerHelper("addOne",function(index,options){
				   return parseInt(index)+1+(json.result.pageNo-1)*json.result.pageSize;
			});
            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getCheckLinkmanData",
                container: $("#onClickDataTable"),
                data:json
            });
            $("#onClickDataTable").attr("comid",id);
            pageHtml(json,$(".layPage"))
    		$(".layPage").show();
        }
		
    })
}
function memberlinkmanEdit(obj){
	var id = $(obj).parents("tr").attr("comid");
	mccmsa.ajax({
        url:"users/getEmergencyContactById/"+id,
        method:"GET",
        success:function(json){
        	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getCheckLinkmanEdit",
                container: $("#onClickDataTable"),
                data:json.result
            });
        	$(".layPage").hide();
        }
    })
}
function memberlinkmanEditPost(obj){
	mccmsa.ajax({
        url:"users/editContact",
        method:"POST",
        data:{
        	"id":$(obj).attr("linkId"),
        	"accountId":$(".memberNav").attr("comId"),
        	"name":$("#name").val(),
        	"relation":$("#relation").val(),
        	"phone":$("#phone").val()
        },
        success:function(json){
        	alert(json.message);
        	memberlinkmanData();
        }
    })
}



function memberlinkmanNew(){
	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
        templateId: "getCheckLinkmanNew",
        container: $("#onClickDataTable")
    });
    $(".layPage").hide();
}
function memberlinkmanNewPost(){
	mccmsa.ajax({
        url:"users/newContact",
        method:"POST",
        data:{
        	"accountId":$(".memberNav").attr("comId"),
        	"name":$("#name").val(),
        	"relation":$("#relation").val(),
        	"phone":$("#phone").val()
        },
        success:function(json){
        	alert(json.message);
        	memberlinkmanData();
        }
		
    })
}



function memberCheckupReporting(pageNo,id){		//体检报告
	//给栏目表录入数据
	if(!pageNo){pageNo=1}		//分页页数
	if(!id){id=$(".memberNav").attr("comid")}
	mccmsa.ajax({
        url:"admin/report/"+id+"/getPhysicalReportAll?pageNo="+pageNo+"&pageSize=8",
        method:"GET",
        success:function(json){
        	for(var i in json.result.resultList){
        		json.result.resultList[i].reportDate=returnDate(json.result.resultList[i].reportDate);
        		json.result.resultList[i].createTime=returnDate(json.result.resultList[i].createTime);
        		if(json.result.resultList[i].filePath){
        			json.result.resultList[i].filePath=json.result.resultList[i].filePath.substring(1);
        		}
        	}
        	Handlebars.registerHelper("addOne",function(index,options){
				   return parseInt(index)+1+(json.result.pageNo-1)*json.result.pageSize;
			});
            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getCheckupReporting",
                container: $("#onClickDataTable"),
                data:json
            });
            $("#onClickDataTable tr:eq(0)").attr("comId",id);
            pageHtml(json,$(".layPage"));
            $(".layPage").show();
        }
    })
}
//编辑
function getCheckupReportingEdit(obj){
	mccmsa.ajax({
        url:"admin/report/getPhysicalReport/"+$(obj).parents("tr").attr("comId"),
        method:"Get",
        success:function(json){
        	json.result.reportDate=returnDate(json.result.reportDate);
        	json.result.createTime=returnDate(json.result.createTime);

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getCheckupReportingEdit",
                container: $("#onClickDataTable"),
                data:json.result
            });
            
            if(json.result.filePath!=null){
				$("#file").attr("src",json.result.filePath)
				$("#file").parent().find(".shadeFile").html(json.result.filePath.substring(json.result.filePath.lastIndexOf("/")+1))
			}
            
            laydate({
                elem: '#reportDate',
                istime: true,
        		format: 'YYYY-MM-DD hh:mm:ss', // 分隔符可以任意定义，该例子表示只显示年月
            });
            laydate({
                elem: '#createTime',
                istime: true,
        		format: 'YYYY-MM-DD hh:mm:ss', // 分隔符可以任意定义，该例子表示只显示年月
            });
            $("#getCheckupReportingEditPost").attr("comId",$(obj).parents("tr").attr("comId"));
            $("#onClickDataTable").show();
            $("#VipList,.layPage").hide(); 
        }
    })
}
function getCheckupReportingEditPost(obj){
	mccmsa.ajax({
        url:"admin/report/modifyPhysicalReport",
        method:"post",
        data:{
        	"id":$(obj).attr("comId"),
        	"fileName":$("#fileName").val(),
        	"filePath":$(".shadeFile").attr("path"),
        	"reportDate":$("#reportDate").val(),
        	"reportProvider":$("#reportProvider").val(),
        	"createTime":$("#createTime").val(),
        	"status":"1",
        	"memberId":$(".memberNav").attr("comId"),
        },
        success:function(json){
        	alert(json.message);
        	memberCheckupReporting("",$(".memberNav").attr("comId"));
        }
    })
}
//新增
function getCheckupReportingNew(obj){
	mccmsa.ajax({
        url:"admin/report/getPhysicalReport/1",
        method:"Get",
        success:function(json){
            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getCheckupReportingNew",
                container: $("#onClickDataTable"),
                data:json.result
            });
            
            laydate({
                elem: '#reportDate',
                istime: true,
        		format: 'YYYY-MM-DD hh:mm:ss', // 分隔符可以任意定义，该例子表示只显示年月
            });

            $("#onClickDataTable").show();
            $("#VipList,.layPage").hide(); 
        }
    })
}
function getCheckupReportingPost(obj){
	mccmsa.ajax({
        url:"admin/report/addPhysicalReport",
        method:"post",
        data:{
        	"fileName":$("#fileName").val(),
        	"filePath":$(".shadeFile").attr("path"),
        	"reportDate":$("#reportDate").val(),
        	"reportProvider":$("#reportProvider").val(),
        	"memberId":$(".memberNav").attr("comId"),
        },
        success:function(json){
        	alert(json.message);
        	memberCheckupReporting("",$(".memberNav").attr("comId"));
        }
    })
}

function isMemberCheck(){		//判断是否进入会员查看页面
	if($(".memberNav").css("display")!="none"){
		$("#onClickDataTable").css({
			"borderTop":"1px solid #dfdfdf",
			"borderLeft":"1px solid #dfdfdf"
		})
	}else{
		
		$("#onClickDataTable").css({
			"border":"0",
		})
	}
}

//编辑
function memberEdit(obj){
	mccmsa.ajax({
        url:"member/getMemberInfo/"+$(obj).parents("tr").attr("comId"),
        method:"GET",
        success:function(json){
        	json.result.birthday=returnDateDay(json.result.birthday);
        	
        	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navEdit",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getEditData",
                container: $("#onClickDataTable"),
                data:json
            });
            $("#onClickDataTable").show();
            $("#memberList,.memberNav").hide();
            isMemberCheck();//判断是否查看，否则table的border为0
            $("#status option[value='"+json.result.status+"']").attr("selected","selected");
            $("#isBlock option[value='"+json.result.isBlock+"']").attr("selected","selected");
            $("#regisFrom option[value='"+json.result.regisFrom+"']").attr("selected","selected");
            
            if(json.result.userHead!=null){
				$("#preview").attr("src","upload/enterprice/image/"+json.result.userHead);
				$("#preview").parent().find(".shadeFile").html(json.result.userHead.substring(json.result.userHead.lastIndexOf("/")+1))
			}
            if(!json.result.identity[0]){json.result.identity[0]=""}
            if(!json.result.memberLevel){json.result.memberLevel=""}
            getDrVip(json.result.identity[0].id,json.result.memberLevel.id);
            laydate({
                elem: '#birthday',
        		format: 'YYYY-MM-DD', // 分隔符可以任意定义，该例子表示只显示年月
            });
        }
    })
}
function getDrVip(ide,vip){		//获取vip和身份
	mccmsa.ajax({
        url:"users/getAll",
        method:"Get",
        success:function(json){
        	var html = '';
        	for(var i in json.result){
        		html+='<option value="'+json.result[i].id+'">'+json.result[i].name+'</option>'
        	}
        	$("#isIdentity").html(html);
        	$("#isIdentity option[value='"+ide+"']").attr("selected","selected");
        }
    })   
    mccmsa.ajax({
        url:"users/getLevel",
        method:"Get",
        success:function(json){
        	var html = '';
        	for(var i in json.result.resultList){
        		html+='<option value="'+json.result.resultList[i].id+'">'+json.result.resultList[i].level+'</option>'
        	}
        	
        	$("#isVip").html(html);
        	$("#isVip option[value='"+vip+"']").attr("selected","selected");
        }
    })
}
function memberEditPost(){
	mccmsa.ajax({
        url:"member/updateAccountInfo",
        method:"POST",
        data:{
        	"id":$("#onClickDataTable>tr:eq(0)").attr("comId"),
        	"username":$("#username").val(),
        	"nickname":$("#nickname").val(),
        	"mobile":$("#mobile").val(),
        	"sex":$("#sex").val(),
        	"realName":$("#realName").val(),
        	"birthday":$("#birthday").val(),
        	"qq":$("#qq").val(),
        	"email":$("#email").val(),
        	"postcode":$("#postcode").val(),
        	"address":$("#address").val(),
        	"area":$("#area").val(),
        	"userHead":$("#preview").attr("src").substring($("#preview").attr("src").lastIndexOf("/")+1),
        	"regisFrom":$("#regisFrom").val(),
        	"isBlock":$("#isBlock").val(),
        	"idenId":$("#isIdentity").val(),
        	"vipId":$("#isVip").val(),
        	"status":$("#status").val()
        },
        success:function(json){
        	alert(json.message)
        	memberList();
        }
    })
}


//新增
function memberNew(obj){
	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
        templateId: "navNewData",
        container: $("#pathContainer")
    });

    mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
        templateId: "getNewData",
        container: $("#onClickDataTable")
    });
    $("#onClickDataTable").show();
    $("#memberList,.memberNav").hide();
    getDrVip();
    isMemberCheck();//判断是否查看，否则table的border为0
    setTimeout(function(){laydate({
        elem: '#birthday',
		format: 'YYYY-MM-DD', // 分隔符可以任意定义，该例子表示只显示年月
    }),1000})
    
}
function memberNewPost(username){
	mccmsa.ajax({
        url:"member/addAccount",
        method:"POST",
        data:{
        	"username":$("#username").val(),
        	"password":$("#password").val(),
        	"nickname":$("#nickname").val(),
        	"mobile":$("#mobile").val(),
        	"sex":$("#sex").val(),
        	"realName":$("#realName").val(),
        	"birthday":$("#birthday").val(),
        	"qq":$("#qq").val(),
        	"email":$("#email").val(),
        	"postcode":$("#postcode").val(),
        	"address":$("#address").val(),
        	"area":$("#area").val(),
        	"userHead":$("#preview").attr("src").substring($("#preview").attr("src").lastIndexOf("/")+1),
        	"regisFrom":$("#regisFrom").val(),
        	"isBlock":$("#isBlock").val(),
        	"idenId":$("#isIdentity").val(),
        	"vipId":$("#isVip").val(),
        	"status":$("#status").val()
        },
        success:function(json){
        	alert(json.message);
        	memberList();
        }
    })
}


function memberDel(obj,val){
	$("#myModal").attr("actattid",$(obj).parents("tr").attr("comId"));
	$("#myModal").attr("val",val);
}
function memberDelPost(){
	var val = $("#myModal").attr("val");
	switch(val){
		case "1":
			mccmsa.ajax({
		        url:"member/delMember/"+$("#myModal").attr("actattid"),
		        method:"POST",
		        data:{
		        	//"id":$("#myModal").attr("actattid"),
		        	"_method":"delete"
		        },
		        success:function(json){
		        	alert(json.message);
		        	memberList();
		        	$(".close").click();
		        }
		    })
		break;
		case "2":
			mccmsa.ajax({
		        url:"admin/report/delPhysicalReport/"+$("#myModal").attr("actattid"),
		        method:"DELETE",
		        success:function(json){
		        	memberCheckupReporting("",$(".memberNav").attr("comid"));
		        	$(".close").click();
		        }
		    })
		break;
		case "3":
			mccmsa.ajax({
		        url:"users/deleteDynamic/"+$("#myModal").attr("actattid"),
		        method:"GET",
		        success:function(json){
		        	memberDynamicList();
		        	$(".close").click();
		        }
		    })
		break;
		case "4":
			mccmsa.ajax({
		        url:"users/deleteContact/"+$("#myModal").attr("actattid"),
		        method:"GET",
		        success:function(json){
		        	memberlinkmanData();
		        	$(".close").click();
		        }
		    })
		break;
	}
	
}
/*会员列表end*/


/*动态数据管理列表*/
function dynamicDataList(pageNo){
	 //给栏目表录入数据
	if(!pageNo){pageNo=1}		//分页页数
    mccmsa.ajax({
        url:"users/getDynamicDataList?pageNo="+pageNo+"&pageSize=8",
        method:"Get",
        success:function(json){
        	for(var i in json.result.resultList){
        		json.result.resultList[i].checkTime=returnDate(json.result.resultList[i].checkTime);
        	}
        	Handlebars.registerHelper("addOne",function(index,options){
				   return parseInt(index)+1+(json.result.pageNo-1)*json.result.pageSize;
			});
            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navMain",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getColumnTableData",
                container: $("#ColumnTableData"),
                data:json
            });
			pageHtml(json);		//生成分页
            $("#dynamicDataList").show();
            $("#onClickDataTable").hide(); 
			
            var scrollbarWidth = $('.table-maxHeight')[0].offsetWidth - $('.table-maxHeight')[0].scrollWidth;
            $("table:eq(0)").css("paddingRight",scrollbarWidth);    //获取滚动条宽度并赋值到表头padding-right，对齐
        }
    })
}
function dynamicDataEdit(obj){
	mccmsa.ajax({
        url:"users/getDynamicDataById/"+$(obj).parents("tr").attr("comId"),
        method:"GET",
        success:function(json){
        	json.result.birthday=returnDateDay(json.result.birthday);
        	
        	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navEdit",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getEditData",
                container: $("#onClickDataTable"),
                data:json
            });
            $("#onClickDataTable").show();
            $("#dynamicDataList").hide();
            
        }
    })
}
function dynamicDataEditPost(){
	mccmsa.ajax({
        url:"users/editDynamicData",
        method:"POST",
        data:{
        	"id":$("#onClickDataTable>tbody>tr:eq(0)").attr("comId"),
        	"defecate":$("#defecate").val(),
        	"temperature":$("#temperature").val(),
        	"systolicPressure":$("#systolicPressure").val(),
        	"diastolicPressure":$("#diastolicPressure").val(),
        	"bloodGlucose":$("#bloodGlucose").val(),
        	"heartRate":$("#heartRate").val(),
        	"apptite":$("#apptite").val(),
        	"threeMeals":$("#threeMeals").val(),
        	"fruitsIntale":$("#fruitsIntale").val(),
        	"waterIntake":$("#waterIntake").val(),
        	"runDuration":$("#runDuration").val(),
        	"smoothBowel":$("#smoothBowel").val(),
        	"micturitionUnmber":$("#micturitionUnmber").val()
        },
        success:function(json){
        	alert(json.message);
        	dynamicDataList();
        }
    })
}


//新增
function dynamicDataNew(obj){
	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
        templateId: "navNewData",
        container: $("#pathContainer")
    });

    mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
        templateId: "getNewData",
        container: $("#onClickDataTable")
    });
    $("#onClickDataTable").show();
    $("#dynamicDataList").hide();
    
}
function dynamicDataNewPost(username){
	mccmsa.ajax({
        url:"users/addDynamic",
        method:"POST",
        data:{
        	"accountId":$("#username").val(),
        	"defecate":$("#defecate").val(),
        	"temperature":$("#temperature").val(),
        	"systolicPressure":$("#systolicPressure").val(),
        	"diastolicPressure":$("#diastolicPressure").val(),
        	"bloodGlucose":$("#bloodGlucose").val(),
        	"heartRate":$("#heartRate").val(),
        	"apptite":$("#apptite").val(),
        	"threeMeals":$("#threeMeals").val(),
        	"fruitsIntale":$("#fruitsIntale").val(),
        	"waterIntake":$("#waterIntake").val(),
        	"runDuration":$("#runDuration").val(),
        	"smoothBowel":$("#smoothBowel").val(),
        	"micturitionUnmber":$("#micturitionUnmber").val()
        },
        success:function(json){
        	alert(json.message);
        	dynamicDataList();
        }
    })
}


function dynamicDataDel(obj){
	$("#myModal").attr("actattid",$(obj).parents("tr").attr("comId"));
}
function dynamicDataDelPost(){
	mccmsa.ajax({
        url:"users /deleteDynamic/"+$("#myModal").attr("actattid"),
        method:"GET",
        success:function(json){
        	dynamicDataList();
        	$(".close").click();
        }
    })
}
/*动态数据管理end*/

/*达人管理*/
function intelligentList(){
    mccmsa.ajax({
        url:"users/getAll",
        method:"Get",
        success:function(json){
        	Handlebars.registerHelper("addOne",function(index,options){
				   return parseInt(index)+1;
			});
            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navMain",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getColumnTableData",
                container: $("#ColumnTableData"),
                data:json
            });
            $("#intelligentList").show();
            $("#onClickDataTable,.memberNav").hide(); 
            
            var scrollbarWidth = $('.table-maxHeight')[0].offsetWidth - $('.table-maxHeight')[0].scrollWidth;
            $("table:eq(0)").css("paddingRight",scrollbarWidth);    //获取滚动条宽度并赋值到表头padding-right，对齐
        }
    })
}

//新增
function intelligentNew(obj){
	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
        templateId: "navNewData",
        container: $("#pathContainer")
    });

    mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
        templateId: "getNewData",
        container: $("#onClickDataTable")
    });
    $("#onClickDataTable").show();
    $("#intelligentList").hide(); 
}
function intelligentNewPost(){
	mccmsa.ajax({
        url:"users/addIndentity",
        method:"POST",
        data:{
        	"name":$("#name").val()
        },
        success:function(json){
        	alert(json.message);
        	intelligentList();
        }
    })
}

function intelligentListDel(obj){
	$("#myModal").attr("actattid",$(obj).parents("tr").attr("comId"));
}
function intelligentListDelPost(){
	mccmsa.ajax({
        url:"users/deleteIndentity/"+$("#myModal").attr("actattid"),
        method:"GET",
        success:function(json){
        	intelligentList();
        	$(".close").click();
        }
    })
}
/*达人管理end*/

/*VIP管理*/
function VipList(){
    mccmsa.ajax({
        url:"users/getLevel",
        method:"Get",
        success:function(json){
        	
        	Handlebars.registerHelper("addOne",function(index,options){
				   return parseInt(index)+1+(json.result.pageNo-1)*json.result.pageSize;
			});
            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navMain",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getColumnTableData",
                container: $("#ColumnTableData"),
                data:json
            });
            $("#VipList").show();
            $("#onClickDataTable,.memberNav").hide(); 
            pageHtml(json);	
            var scrollbarWidth = $('.table-maxHeight')[0].offsetWidth - $('.table-maxHeight')[0].scrollWidth;
            $("table:eq(0)").css("paddingRight",scrollbarWidth);    //获取滚动条宽度并赋值到表头padding-right，对齐
        }
    })
}
//编辑
function VipEdit(obj){
	mccmsa.ajax({
        url:"users/getMemberLevelById/"+$(obj).parents("tr").attr("comId"),
        method:"Get",
        success:function(json){
        	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "navEdit",
                container: $("#pathContainer")
            });

            mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
                templateId: "getEditData",
                container: $("#onClickDataTable"),
                data:json
            });
            $("#onClickDataTable").show();
            $("#VipList").hide();
        }
    })
}

function VipEditPost(val){
	mccmsa.ajax({
        url:"users/editLevel",
        method:"POST",
        data:{
        	"id":val,
        	"level":$("#level").val(),
        	"discount":$("#discount").val(),
        	"levelImg":$("#preview").attr("src").substring($("#preview").attr("src").lastIndexOf("/")+1),
        	"status":"1"
        },
        success:function(json){
        	alert(json.message);
        	VipList();
        }
    })
}
//新增
function VipNew(obj){
	mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
        templateId: "navNewData",
        container: $("#pathContainer")
    });

    mccmsa.getHtmlFromLocalTemplate({   //将数据打包到模版丢进容器
        templateId: "getNewData",
        container: $("#onClickDataTable")
    });
    $("#onClickDataTable").show();
    $("#VipList").hide(); 
}
function VipNewPost(){
    mccmsa.ajax({
        url:"users/addLevel",
        method:"POST",
        data:{
        	"level":$("#level").val(),
        	"discount":$("#discount").val(),
        	"levelImg":$("#preview").attr("src").substring($("#preview").attr("src").lastIndexOf("/")+1),
        	"status":"1"
        },
        success:function(json){
        	alert(json.message);
        	VipList();
        }
    })
}

function VipListDel(obj){
	$("#myModal").attr("actattid",$(obj).parents("tr").attr("comId"));
}
function VipListDelPost(){
	mccmsa.ajax({
        url:"users/deleteLevel/"+$("#myModal").attr("actattid"),
        method:"GET",
        success:function(json){
        	VipList();
        	$(".close").click();
        }
    })
}
/*VIP管理end*/


/*论坛管理*/
function forumManageList(val){
	columnManage('1',val);
}
/*论坛管理end*/



/*common function*/
function format(time, format){
    var t = new Date(time);
    var tf = function(i){return (i < 10 ? '0' : '') + i};
    return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a){
        switch(a){
            case 'yyyy':
                return tf(t.getFullYear());
                break;
            case 'MM':
                return tf(t.getMonth() + 1);
                break;
            case 'mm':
                return tf(t.getMinutes());
                break;
            case 'dd':
                return tf(t.getDate());
                break;
            case 'HH':
                return tf(t.getHours());
                break;
            case 'ss':
                return tf(t.getSeconds());
                break;
        }
    })
}
function returnDate(time){		//返回标准格式时间
	return format(time, 'yyyy-MM-dd HH:mm:ss');
}
function returnDateDay(time){		//返回标准格式时间
	return format(time, 'yyyy-MM-dd');
}
function returnStatus(val){
	if(val){
		return "有效活动";
	}else{
		return "无效活动";
	}
}
function returnStatusCon(val){
	if("0"==val){
		return "未通过";
	}else if("1"==val){
		return "已通过";
	}else if("2"==val){
		return "待审核";
	}else{
		return val;
	}
}
function returnStatusMember(val){
	if("1"==val){
		return "启用";
	}else if("0"==val){
		return "禁用";
	}else if("2"==val){
		return "注销";
	}else{
		return val;
	}
}

function returnIsShowInNav(val){
	if(val==1){
		return "是";
	}else{
		return "否";
	}
}
function returnStatusCon(val){
	if(val==1){
		return "已启动";
	}else{
		return "已停用";
	}
}
function pwdsRecord(){
  mccmsa.ajax({
      url:"devicePwdInfo/getPwdInfoRecord",
      method:"post",
      data:{id: $.bbq.getState("id")},
      success:function(data){
          $("#door_title").html(data.result[0].deviceInfo.centerControl.address+" - 临时密码记录");
          mccmsa.getHtmlFromLocalTemplate({
              templateId:"pwds_record_data_table",
              container:$("#pwds_record_data"),
              data:data
          });
      }

  })
}
function pwdToMobile(node){       //发送密码到手机
    var id=$(this).attr("data-id");
    var mobile=$(this).parent().find("input").val();
    if(mobile=="") return;
    mccmsa.ajax({
        url:"",
        method:"post"

    })
}

/**
 * Created by Jay on 2016/5/31.
 */

function safe_set(){
    $(".add_device_form").validate();
    var safe_id=sessionStorage.getItem(id)||3;
    var username=sessionStorage.getItem(name)||"thomas";
    var role=sessionStorage.getItem(role)||3;
    var old_pwd=$(".add_device_form ul li").eq(0).find("input").val();
    var new_pwd=$(".add_device_form ul li").eq(1).find("input").val();
    if(role==1){
        $(".role_change").html("(超级管理员)");
    }
    else if(role==2){
        $(".role_change").html("(管理员)");
    }
    else if(role==3){
        $(".role_change").html("(用户)");
    }
    $(".save_btn").off().unbind().click(function(){
        if($(".add_device_form").valid()){
            var old_pwd=$(".add_device_form ul li").eq(0).find("input").val();
            var new_pwd=$(".add_device_form ul li").eq(1).find("input").val();
            mccmsa.ajax({
                url:"user/updateUserSafe/",
                method:"POST",
                data:{id:safe_id,username:username,oldPassword:old_pwd,authPassword:new_pwd},
                success: function (data) {
                    console.log(data);
                },error:function(data){
                    var r=confirm(data.result);
                }
            })
        }
    })

}
/*客户管理*/
/**
 * Created by Jay on 2016/5/17.
 */
function userManage(){
    //头部按钮
    $.Huitab("#tab_company .tabBar span","#tab_company .tabCon","current","click","0");
    $("#userManage").on("click","#tab_company span,#search_company",function() {
        var type = $("#tab_company .tabBar span.current").attr("search_type");
        var likeStr=$(".search_company").val();
        mccmsa.ajax({
            url: "user/getUserByCondition",
            data: {pageNo:1,pageSize:20,companyType:type,likeStr:likeStr},
            method: "POST",
            success: function (data){
                mccmsa.getHtmlFromLocalTemplate({
                    templateId: "getColumnTableData",
                    container: $("#ColumnTableData"),
                    data: data
                });
                //生成分页

                $("#layPage").createPage({
                    pageCount:data.result.pageCount,
                    current:1,
                    backFn:function(p){
                        mccmsa.ajax({
                            url:"user/getUserByCondition",
                            data:{pageNo:1,pageSize:20,companyType:type,likeStr:likeStr},
                            method:"POST",
                            success:function(data){
                                mccmsa.getHtmlFromLocalTemplate({
                                    templateId:"getColumnTableData",
                                    container: $("#ColumnTableData"),
                                    data:data
                                });
                            }
                        })
                    }
                });
            }
        })
    });
    //底部按钮
    mccmsa.ajax({
        url:"user/getUserByCondition",
        data:{pageNo:1,pageSize:20},
        method:"POST",
        success: function (data) {
            mccmsa.getHtmlFromLocalTemplate({
                templateId: "getColumnTableData",
                container: $("#ColumnTableData"),
                data: data
            });
            //生成分页
            $("#layPage").createPage({
                pageCount: data.result.pageCount,
                current: 1,
                backFn: function (p) {
                    mccmsa.ajax({
                        url: "user/getUserByCondition",
                        data: {pageNo: 1, pageSize: 20},
                        method: "POST",
                        success: function (data) {
                            mccmsa.getHtmlFromLocalTemplate({
                                templateId: "getColumnTableData",
                                container: $("#ColumnTableData"),
                                data: data
                            });
                        }
                    })
                }
            });
        }
    });
    /*查看详情*/
    $("body").on("click",".toLook",function(){
        var id=$(this).attr("data-id");
       mccmsa.goTo("user_manage_detail","user_manage",{id:id});
    });
    Handlebars.registerHelper ("fmtCompanyType", function (value) {
        if(!value) return new Handlebars.SafeString("");
        var arr=value.split(",");
        value="";
        for(var i=0;i<arr.length;i++){
          if(arr[i]==2){
              value+=" - 集中式"
          }else if(arr[i]==1){
              value+=" - 分散式"
          }else if(arr[i]==3){
              value+=" - 长租"
          }else if(arr[i]==4){
              value+=" - 短租"
          }
        }
        value=value.replace("-","");
        return new Handlebars.SafeString("<b>" + value + "</b>");
    });
}
var usermange_username="";
var usermange_id="";
function userManageDetail(){
    var id=$.bbq.getState("id");
    mccmsa.ajax({
        url: "user/getUser/"+id,
        method: "get",
        dataType:"json",
        success: function (data) {
            usermange_username=data.result.username;
            usermange_id=data.result.id;
            $.ajax({
                url:"contractInfo/getUserContractInfos",
                data:{"username":data.result.username},
                method: "post",
                dataType:"json",
                success:function(msg){
                    data.ht=msg.result;
                    mccmsa.getHtmlFromLocalTemplate({
                        templateId: "user_manage_detail",
                        container: $("#mainContainer"),
                        data: data
                    });
                }
            });
        }
    });
}
function freezeContractInfo(node,type){            //冻结合同
    var id=$(node).attr("data-id");
    if(type==0){//冻结
        mccmsa.ajax({
            url:"contractInfo/freezeContractInfo/"+id,
            dataType:"json",
            method:"post",
            success:function(data){
                if(data.status=="200"){
                    layer.msg("冻结成功");
                    $(node).parent().html('<a class="btn btn-warning radius" href="javascript:" data-id="'+id+'" onclick="freezeContractInfo(this,1)">解冻远程管理</a>')

                }
            }
        })
    }else{   //解冻
        mccmsa.ajax({
            url:"contractInfo/unfreezeContractInfo/"+id,
            dataType:"json",
            method:"post",
            success:function(data){
                if(data.status=="200"){
                    layer.msg("解冻成功");
                    $(node).parent().html('<a class="btn btn-primary radius" href="javascript:" data-id="'+id+'" onclick="freezeContractInfo(this,0)">冻结远程管理</a>')
                }
            }
        })
    }
}
function addHt(){//添加合同
    var json=$("#addHtForm").serializeJson();
    json.username=$("#logusername").attr("data-username");
    mccmsa.ajax({
        url:"contractInfo/addContractInfo",
        method:"post",
        data:json,
        dataType:"json",
        success:function(data){
            if(data.status=='200'){
                layer.msg("添加成功!");
                $("#ht_table tbody").append('<tr><td class="col-4">'+json.contractNum+'</td> <td class="col-4">'+json.beginTime+' 至'+json.endTime+' </td> <td class="col-4"> <a class="btn btn-primary radius" href="javascript:" data-id='+data.result.id+' onclick="freezeContractInfo(this,0)">冻结远程管理</a> </td> </tr>');
            }else{
                layer.msg(data.message)
            }
        }
    });
    $('#addHt').modal('hide');
}
function subEditUser(){   //提交修改用户信息
        var userData=$("#userInfo").serializeJson();
        userData.companyType=userData.companyType.join(",");
        userData.id=usermange_id;
        mccmsa.ajax({
            url:"user/updateUserInfo",
            method:"post",
            data:userData,
            dataType:"json",
            success:function(data){
                if(data.status=='200'){
                    layer.msg("修改成功");
                }else{
                    layer.msg(data.message);
               }
            }
        });
}
function freezeUser(id,status){       //冻结解冻用户
    if(status==1){
        status=2
    }else if(status==2){
        status=1
    }
    mccmsa.ajax({
        url:"user/freezeUser",
        method:"post",
        data:{id:id,status:status},
        dataType:"json",
        success:function(data){
            if(data.status=="200"){
                layer.msg("操作成功");
                if(status==1){
                  $("#freezeUserop").html('<a href="javascript:" class="f-r c-primary f-14" onclick="freezeUser('+id+',1)">冻结帐号</a>');
                }else if(status==2){
                  $("#freezeUserop").html('<a href="javascript:" class="f-r c-warning f-14" onclick="freezeUser('+id+',2)">解冻帐号</a>')
                }
            }else{
                layer.msg(data.message);
            }
        }
    })
}
function delUser(id){
    if(confirm('您确定要删除吗？')){
        mccmsa.ajax({
            url:"user/freezeUser",
            method:"post",
            data:{id:id,status:0},
            dataType:"json",
            success:function(data){
                if(data.status=="200"){
                    layer.msg("操作成功");
                    mccmsa.goBack();
                }else{
                    layer.msg(data.message);
                }
            }
        })
    }
}
function showXqHt(id,contractNum,beginTime,endTime){           //显示续期合同
    var node=$('#xqHt');
    node.find("input[name='id']").val(id);
    node.find("#xqht_contractNum").val(contractNum);
    node.find("#xqht_beginTime").val(beginTime);
    node.find("input[name='endTime']").val(endTime);
    node.modal('show');
}
function xqHt(){              //提交续期合同
    var ht=$("#xqHtForm").serializeJson();
    $('#xqHt').modal('hide');
    mccmsa.ajax({
        url:"contractInfo/renewalContractInfo",
        method:"post",
        data:ht,
        dataType:"json",
        success:function(data){
            if(data.status=='200'){
                layer.msg("续期成功");
                mccmsa.goTo("user_manage_detail","user_manage",{id:$.bbq.getState("id")});
            }else{
                layer.msg(data.message);
            }
        }
    });
}
$('body').on("click",'.showAddHt', function (e) {
    $('#addHt').modal('show');
});
Handlebars.registerHelper ("companyTypeJude", function (value,value2) {
    if(!value) return "";
    if(value.indexOf(value2)!=-1){
        return "checked";
    }
    return "";
});